package YDLControl;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Dictionary;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import DAO.DBHelper;
import DAO.DBServices;

import DAO.DBServices;

import org.ksoap2.serialization.*;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.xmlpull.v1.XmlPullParserException;
import java.math.*;

@SuppressLint("SimpleDateFormat")
public class Control {
	
	//第一个成员：string代表table时间段
	//第二个成员：double数组，代表每个运动数值
	//第三个成员：iShowType 0时间，1距离，2卡路里，3速度
	//第四个成员：iTimeType 0按日，1按周，2按月，3按年
	String strErrorMessage = "";
	private double[] oneDaySummary(String startTime, String endTime, Context context, String type, int userID)
	{
		String sql = "";
		double[] result = new double[2880];
		for (int i = 0; i < result.length; i++)
		{
			result[i] = 0.0;
		}
		if (type == "speed")
		{
			sql = "select AverageSpeed as "+type+",TrackDate from XFIT_Speed_Detail where UserID="+String.valueOf(userID)+" and TrackDate between '"+startTime + "' and '" + endTime + "' order by TrackDate";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			
			if (tempRe.size() != 0)
			{
				int startNum = 0;
				for (int i = 0; i < tempRe.size(); i++)
				{
					String[] tempTime = tempRe.get(i).get("TrackDate").toString().split(" ");
					String[] tempp = tempTime[1].split(":");
					int hour =Integer.parseInt(tempp[0]);
					int min =Integer.parseInt(tempp[1]);
					int sec = (int)Double.parseDouble(tempp[2]);
					int secondsAll =hour*3600+min*60+sec;
					int numOf30s = secondsAll / 30;
					result[numOf30s] = Double.parseDouble(tempRe.get(i).get(type).toString());
					if (i == 0)
					{
						startNum = numOf30s;
					}
				}
				
				for (int i = 0; i < result.length; i++)
				{
					if (result[i] == 0.0 && i != 0 && result[i-1] != 0.0)
					{
						result[i] = result[i - 1];
					}
				}
			}
			return result;
		}
		else if (type == "Distance")
		{
			sql = "select (AverageSpeed/3600)*TimeSpan as "+type+",TrackDate from XFIT_Speed_Detail where UserID="+String.valueOf(userID)+" and TrackDate between '"+startTime + "' and '" + endTime + "' order by TrackDate";
		}
		else if (type == "SportTime")
		{
			sql = "select TimeSpan as SportTime,TrackDate from XFIT_Speed_Detail where UserID="+String.valueOf(userID)+" and TrackDate between '"+startTime + "' and '" + endTime + "' order by TrackDate";;
		}
		else
		{
			sql = "select "+type+",Track_Date as TrackDate from XFIT_Tracking_Detail where UserID="+String.valueOf(userID)+" and TrackDate between '" + startTime + "' and '" + endTime + "' order by TrackDate";
		}
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		if (tempRe.size() != 0)
		{
			int startNum = 0;
			double tempresult1 = 0.0;//the accumulative value
			for (int i = 0; i < tempRe.size(); i++)
			{
				String[] tempTime = tempRe.get(i).get("TrackDate").toString().split(" ");
				String[] tempp = tempTime[1].split(":");
				int hour =Integer.parseInt(tempp[0]);
				int min =Integer.parseInt(tempp[1]);
				int sec = (int)Double.parseDouble(tempp[2]);
				int secondsAll =hour*3600+min*60+sec;
				int numOf30s = secondsAll / 30;
				tempresult1 += Double.parseDouble(tempRe.get(i).get(type).toString());
				result[numOf30s] = tempresult1;
				if (i == 0)
				{
					startNum = numOf30s;
				}
			}
			
			for (int i = startNum + 1; i < result.length; i++)
			{
				if (result[i] == 0.0 && i != 0 && result[i-1] != 0.0)//当前元素为0，上一个元素不为0且当前元素不是第一个元素
				{
					result[i] = result[i - 1];
				}
			}
		}
		return result;
	}
	
	
	
	//通过用户所选日期得到此日期所在的日，周，月或年的报表数据
	/**
	 * @param selDate 用户所选日期
	 * @param iShowType 所要显示的类型 0时间，1距离，2卡路里，3速度
	 * @param iTimeType 所需显示的时间类型 0按日，1按周，2按月，3按年
	 * @param UserID  用户id
	 * @param context
	 * @return result key("iTimeType"时间类型,
	 * 					  "iShowType"显示类型,
	 * 					  "timeBucket"时间段,
	 *                    "startTime"开始时间,
	 *                    "endTime"结束时间,
	 *                    "yArray"y轴的值)
	 * @throws ParseException
	 */
	@SuppressWarnings("deprecation")
	public Hashtable getDAOChartInfo(Date selDate, int iShowType, int iTimeType, int UserID, Context context) throws ParseException
	{
		double adjustData = getAdjustmentData(UserID, context);//用户调整数据
		Hashtable result = new Hashtable();
		result.put("iTimeType", iTimeType);
		result.put("iShowType", iShowType);
		String timeBucket = "";
		double[] values;
		String startTime = "";
		String endTime = "";
		if (iShowType == 2)//卡路里
		{
			if (iTimeType == 1)//按周
			{
				Hashtable temp = getTimeBucket(selDate, iTimeType);
				timeBucket = temp.get("TimeBucket").toString();
				
				
				startTime = temp.get("StartTime").toString();
				endTime = temp.get("EndTime").toString();
                                if(startTime.length() > 10)
				{	
			            startTime = startTime.substring(0, 19);
				}
				if(endTime.length() > 10)
                                {
				    endTime = endTime.substring(0, 19) + ".999";
                                }
				String sql = "SELECT Calorie,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				DBServices ds = new DBServices();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Calorie").toString())*adjustData;
					 //字符串中的日期格式  
			        DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", (Date)temp.get("StartTimeUtil"));
				result.put("endTime", (Date)temp.get("EndTimeUtil"));
			}
			else if (iTimeType == 2)//按月
			{
				int dayNum = getTheDayNumOfMonth(selDate.getYear(),selDate.getMonth());//取日期所在月份的天数
				Hashtable temp = getTimeBucket(selDate, iTimeType);
				timeBucket = temp.get("TimeBucket").toString();
				
				
				startTime = temp.get("StartTime").toString();
				endTime = temp.get("EndTime").toString();	
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				String sql = "SELECT Calorie,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				DBServices ds = new DBServices();
				tempRe = ds.ExecuteReader1(sql,context);
				
				if (tempRe.size() == 0)
				{
					return result;
				}
				
				double[] yArray = new double[tempRe.size()];
				
				
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Calorie").toString())*adjustData;
					 //字符串中的日期格式  
			        DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", (Date)temp.get("StartTimeUtil"));
				result.put("endTime", (Date)temp.get("EndTimeUtil"));
			}
			else if (iTimeType == 3)//按年
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(selDate.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					
					yArray[i] = getMonthSum(temp, UserID, context,iShowType)*adjustData;
				}
				result.put("timeBucket", String.valueOf(selDate.getYear() + 1900) + "年1月~12月");
				result.put("yArray", yArray);
				Date startTT = new Date(selDate.getYear(), 0, 1);
				Date endTT = new Date(selDate.getYear(), 12, 31);
				result.put("startTime", startTT);
				result.put("endTime", endTT);
			}
			else if (iTimeType == 0)//按日
			{
//				double[] yArray = new double[24];
//				Date temp = new Date(selDate.getTime());
//				for (int i = 0; i < 24; i++)
//				{
//					temp.setHours(i);
//					temp.setMinutes(1);
//					temp.setSeconds(1);
//					
//					yArray[i] = getHourSum(temp, UserID, context, iShowType);
//				}
//				
//				result.put("timeBucket", selDate.toString());
//				result.put("yArray", yArray);
				//String sql = "select * from ";
				Hashtable timeBucket1 = getTimeBucket(selDate, iTimeType);
				startTime = timeBucket1.get("StartTime").toString();
				endTime = timeBucket1.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				double[] yArray = oneDaySummary(startTime,endTime,context,"Calorie",UserID);
				result.put("yArray", yArray);
				result.put("startTime", (Date)timeBucket1.get("StartTimeUtil"));
				result.put("endTime", (Date)timeBucket1.get("EndTimeUtil"));
				java.sql.Date tb = new java.sql.Date(selDate.getTime());
				result.put("timeBucket", tb.toString());
			}
		}
		else if (iShowType == 0)
		{
			Hashtable temp = getTimeBucket(selDate, iTimeType);
			DBServices ds = new DBServices();
			result = getOneReport(String.valueOf(UserID), iTimeType, temp.get("StartTime").toString(), temp.get("EndTime").toString(), iShowType, context, adjustData, ds, 0, 0);
			result.put("timeBucket", temp.get("TimeBucket").toString());
		}
		else if (iShowType == 1)//按距离
		{
			if (iTimeType == 1)//按周
			{
				Hashtable temp = getTimeBucket(selDate, iTimeType);
				timeBucket = temp.get("TimeBucket").toString();
				
				
				startTime = temp.get("StartTime").toString();
				endTime = temp.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				String sql = "SELECT Distance,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				DBServices ds = new DBServices();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData;
					 //字符串中的日期格式  
			        DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", (Date)temp.get("StartTimeUtil"));
				result.put("endTime", (Date)temp.get("EndTimeUtil"));
			}
			else if (iTimeType == 2)//按月
			{
				Hashtable temp = getTimeBucket(selDate, iTimeType);
				timeBucket = temp.get("TimeBucket").toString();
				
				
				startTime = temp.get("StartTime").toString();
				endTime = temp.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				String sql = "SELECT Distance,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				DBServices ds = new DBServices();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				int dayNum = getTheDayNumOfMonth(selDate.getYear(),selDate.getMonth());//取日期所在月份的天数
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData;
					 //字符串中的日期格式  
			        DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				
				result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", (Date)temp.get("StartTimeUtil"));
				result.put("endTime", (Date)temp.get("EndTimeUtil"));
			}
			else if (iTimeType == 3)//按年
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(selDate.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					
					yArray[i] = getMonthSum(temp, UserID, context,iShowType)*adjustData;
				}
				
				result.put("timeBucket", String.valueOf(selDate.getYear()+1900) + "年1月~12月");
				result.put("yArray", yArray);
				
				Date startDate = new Date(selDate.getYear(),0,1);
				Date endDate = new Date(selDate.getYear(),11,1);
				result.put("startTime", startDate);
				result.put("endTime", endDate);
			}
			else if (iTimeType == 0)//按日
			{
//				double[] yArray = new double[24];
//				Date temp = new Date(selDate.getTime());
//				for (int i = 0; i < 24; i++)
//				{
//					temp.setHours(i);
//					temp.setMinutes(1);
//					temp.setSeconds(1);
//					
//					yArray[i] = getHourSum(temp, UserID, context, iShowType);
//				}
//				
//				result.put("timeBucket", selDate.toString());
//				result.put("yArray", yArray);
				Hashtable timeBucket1 = getTimeBucket(selDate, iTimeType);
				startTime = timeBucket1.get("StartTime").toString();
				endTime = timeBucket1.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				double[] yArray = oneDaySummary(startTime,endTime,context,"Distance",UserID);
				result.put("yArray", yArray);
				result.put("startTime", (Date)timeBucket1.get("StartTimeUtil"));
				result.put("endTime", (Date)timeBucket1.get("EndTimeUtil"));
				java.sql.Date tb = new java.sql.Date(selDate.getTime());
				result.put("timeBucket", tb.toString());
			}
		}
		else if (iShowType == 3)//平均速度
		{
			if (iTimeType == 1)//按周
			{
				Hashtable temp = getTimeBucket(selDate, iTimeType);
				timeBucket = temp.get("TimeBucket").toString();
				startTime = temp.get("StartTime").toString();
				endTime = temp.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				String sql = "SELECT Distance,SummaryDate,SportTime FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				DBServices ds = new DBServices();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = (Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData)/Double.parseDouble(tempRe.get(i).get("SportTime").toString());
					 //字符串中的日期格式  
			        DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				
				
				result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", (Date)temp.get("StartTimeUtil"));
				result.put("endTime", (Date)temp.get("EndTimeUtil"));
			}
			else if (iTimeType == 2)//按月
			{
				Hashtable temp = getTimeBucket(selDate, iTimeType);
				timeBucket = temp.get("TimeBucket").toString();
				
				
				startTime = temp.get("StartTime").toString();
				endTime = temp.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				String sql = "SELECT Distance,SummaryDate,SportTime FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				DBServices ds = new DBServices();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				int dayNum = getTheDayNumOfMonth(selDate.getYear(),selDate.getMonth());//取日期所在月份的天数
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = (Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData)/Double.parseDouble(tempRe.get(i).get("SportTime").toString());
					 //字符串中的日期格式  
			        DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				result.put("timeBucket", timeBucket);
				result.put("yArray", yArray);
				result.put("startTime", (Date)temp.get("StartTimeUtil"));
				result.put("endTime", (Date)temp.get("EndTimeUtil"));
			}
			else if (iTimeType == 3)
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(selDate.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					yArray[i] = getMonthSum(temp, UserID, context,iShowType)*adjustData;
				}
				result.put("timeBucket", String.valueOf(selDate.getYear() + 1900) + "年1月~12月");
				result.put("yArray", yArray);
				Date startDate = new Date(selDate.getYear(),0,1);
				Date endDate = new Date(selDate.getYear(),11,1);
				result.put("startTime", startDate);
				result.put("endTime", endDate);
			}
			else if (iTimeType == 0)//按日
			{
//				double[] yArray = new double[24];
//				Date temp = new Date(selDate.getTime());
//				for (int i = 0; i < 24; i++)
//				{
//					temp.setHours(i);
//					temp.setMinutes(1);
//					temp.setSeconds(1);
//					
//					yArray[i] = getHourSum(temp, UserID, context, iShowType);
//				}
//				
//				result.put("timeBucket", selDate.toString());
//				result.put("yArray", yArray);
				Hashtable timeBucket1 = getTimeBucket(selDate, iTimeType);
				startTime = timeBucket1.get("StartTime").toString();
				endTime = timeBucket1.get("EndTime").toString();
                                if(startTime.length() > 10)
                                {
				     startTime = startTime.substring(0, 19);
                                }
                                if(endTime.length() > 10)
                                {
				     endTime = endTime.substring(0, 19) + ".999";
                                }
				double[] yArray = oneDaySummary(startTime,endTime,context,"speed",UserID);
				result.put("startTime", (Date)timeBucket1.get("StartTimeUtil"));
				result.put("endTime", (Date)timeBucket1.get("EndTimeUtil"));
				result.put("yArray", yArray);
				java.sql.Date tb = new java.sql.Date(selDate.getTime());
				result.put("timeBucket", tb.toString());
			}
		}
		return result;
	}
	
	
	
	/**
	 * @param date
	 * @param UserId
	 * @param context
	 * @param iShowType
	 * @return
	 */
	private double getMonthSum(Date date, int UserId, Context context,int iShowType)
	{
		double result = 0.0;
		if (iShowType == 2)
		{
		
			Hashtable timeBucket = new Hashtable();
			timeBucket = getTimeBucket(date, 2);
			String sql = "SELECT Sum(Calorie) as monthCalorie FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserId)+" AND SummaryDate BETWEEN '"+timeBucket.get("StartTime").toString()+"' AND '"+timeBucket.get("EndTime").toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			if (tempRe.size() == 0)
			{
				return result;
			}
		//if ((Hashtable)(tempRe.get(0)).isEmpty())
			if(tempRe.get(0).get("monthCalorie").toString() != "")
			{
				result = Double.parseDouble(tempRe.get(0).get("monthCalorie").toString());
			} 
			else
				result = 0.0;
			}
		else if (iShowType == 1)
		{
			Hashtable timeBucket = new Hashtable();
			timeBucket = getTimeBucket(date, 2);
			String sql = "SELECT Sum(Distance) as monthDistance FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserId)+" AND SummaryDate BETWEEN '"+timeBucket.get("StartTime").toString()+"' AND '"+timeBucket.get("EndTime").toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			
			if (tempRe.size() == 0)
			{
				return result;
			}
			
			if (tempRe.get(0).get("monthDistance").toString() != "")
				result = Double.parseDouble(tempRe.get(0).get("monthDistance").toString());
			else
				result = 0.0;
		}
		else if (iShowType == 3)
		{
			Hashtable timeBucket = new Hashtable();
			timeBucket = getTimeBucket(date, 2);
			String sql = "SELECT Sum(Distance) as monthDistance,sum(SportTime) as monthSportTime FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserId)+" AND SummaryDate BETWEEN '"+timeBucket.get("StartTime").toString()+"' AND '"+timeBucket.get("EndTime").toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			if (tempRe.get(0).get("monthDistance").toString() != "" && tempRe.get(0).get("monthSportTime").toString() != "")
			{
				result = Double.parseDouble(tempRe.get(0).get("monthDistance").toString())/Double.parseDouble(tempRe.get(0).get("monthSportTime").toString());
			}
			else
				result = 0.0;
		}
		else if (iShowType == 0)
		{
			Hashtable timeBucket = new Hashtable();
			timeBucket = getTimeBucket(date, 2);
			String sql = "SELECT sum(SportTime) as monthSportTime FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserId)+" AND SummaryDate BETWEEN '"+timeBucket.get("StartTime").toString()+"' AND '"+timeBucket.get("EndTime").toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			if (tempRe.get(0).get("monthSportTime").toString() != "")
			{
				result = Double.parseDouble(tempRe.get(0).get("monthSportTime").toString());
			}
			else
				result = 0.0;
		}
		return result;
	}
	
	
	private double getHourSum(Date date, int UserId, Context context,int iShowType)
	{
		double result = 0.0;
		Date start = new Date(date.getTime());
		Date end = new Date(date.getTime());
		
		start.setMinutes(0);//一个小时的0分0秒~59分59秒
		start.setSeconds(0);
		
		end.setMinutes(59);
		end.setSeconds(59);
		
		java.sql.Date startD = new java.sql.Date(start.getTime());
		java.sql.Date endD = new java.sql.Date(end.getTime());
		if (iShowType == 2)
		{
			String sql = "SELECT Sum(Calorie) as hourCalorie FROM XFIT_Per_Running WHERE UserID="+String.valueOf(UserId)+" AND StartTime BETWEEN '"+startD.toString()+"' AND '"+endD.toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			if (tempRe.get(0).get("hourCalorie").toString() != "")
			{
				result = Double.parseDouble(tempRe.get(0).get("hourCalorie").toString());
			}
			else
				result = 0.0;
		}
		else if (iShowType == 1)
		{
			String sql = "SELECT Sum(Distance) as hourDistance FROM XFIT_Per_Running WHERE UserID="+String.valueOf(UserId)+" AND StartTime BETWEEN '"+startD.toString()+"' AND '"+endD.toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			if (tempRe.get(0).get("hourDistance").toString() != "")
			{
				result = Double.parseDouble(tempRe.get(0).get("hourDistance").toString());
			}
			else
				result = 0.0;
		}
		else if (iShowType == 3)
		{
			String sql = "SELECT Sum(Distance) as hourDistance,sum(SportTime) as hourSportTime FROM XFIT_Per_Running WHERE UserID="+String.valueOf(UserId)+" AND StartTime BETWEEN '"+startD.toString()+"' AND '"+endD.toString()+"'";
			ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
			DBServices ds = new DBServices();
			tempRe = ds.ExecuteReader1(sql,context);
			if (tempRe.get(0).get("hourDistance").toString() != "" && tempRe.get(0).get("hourSportTime").toString() != "")
			{
				result = Double.parseDouble(tempRe.get(0).get("hourDistance").toString())/Double.parseDouble(tempRe.get(0).get("hourSportTime").toString());
			}
			else
				result = 0.0;
		}
		
		return result;
	}
	
	//取得某个月的天数
	private int getTheDayNumOfMonth(int year, int month)
	{
		int dayNum = 0;
		Calendar time=Calendar.getInstance();
		time.clear();
		time.set(Calendar.YEAR,year);
		time.set(Calendar.MONTH, month);
		dayNum = time.getActualMaximum(Calendar.DAY_OF_MONTH);//取日期所在月份的天数
		return dayNum;
	}
	
	private double getAdjustmentData(int UserId, Context context)
	{
		double result = 1.0;
		String sql = "select User_Adjustment_Data from XFIT_User_Info where UserID=" + String.valueOf(UserId);
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		if (tempRe.size() == 0)
		{
			return result;
		}
	    result = Double.parseDouble(tempRe.get(0).get("User_Adjustment_Data").toString());
		return result;
	}
	
	public void buildDatabase(Context context)
	{
		DBServices ds = new DBServices();
		ds.buildDB(context);
	}
	
	//收藏报表
	/*	String tName = "XFIT_Day_Summary";   //表名
	ContentValues cValue = new ContentValues();
	cValue.put("DaySummaryID", String.valueOf(i));
	cValue.put("SummaryDate", "'2011-11-08 00:00:00.000'");
	cValue.put("UserID", "91");
	cValue.put("SportTime", "3060.00");
	cValue.put("Calorie", "0.2269900000");
	cValue.put("Distance", "112.4151949025"); //插入的行信息*/
	
	//日期只存年月日即可，若是按照日来算，那么起始时间和终止时间相同
	/**
	 * @param context
	 * @param startDate 日期只存年月日即可，若是按照日来算，那么起始时间和终止时间相同
	 * @param endDate
	 * @param weekMonthYear
	 * @param userId
	 * @param showType
	 * @return
	 */
	public int storeReport(Context context, Date startDate, Date endDate, int weekMonthYear, int userId, int showType)
	{		
		int result = -1;
		String tName = "MonthWeekYearReport";
		ContentValues cValue = new ContentValues();
		Timestamp startD = new Timestamp(startDate.getTime());
		//java.sql.Date startD = new java.sql.Date(startDate.getTime());
		cValue.put("StartDate", startD.toString());
		//java.sql.Date endD = new java.sql.Date(endDate.getTime());
		Timestamp endD = new Timestamp(endDate.getTime());
		cValue.put("EndDate",  endD.toString());
		cValue.put("WeekMonthYear", String.valueOf(weekMonthYear));
		cValue.put("UserId", String.valueOf(userId));
		cValue.put("ShowType", String.valueOf(showType)); //插入的行信息
		
		long tempRe = 0;
		DBServices dbs = new DBServices();
		tempRe = dbs.ExecuteInsertSingle(cValue, context, tName);
		if (tempRe != -1)
		{
			String sql = "select max(ID) as ID from MonthWeekYearReport";
			DBServices ds = new DBServices();
			ArrayList<Dictionary> tempRee = ds.ExecuteReader1(sql,context);
			int maxid = Integer.parseInt(tempRee.get(0).get("ID").toString());
			result = maxid;
		}
		return result;
	}
	
	public boolean haveDataOrNot(Context context)
	{
		boolean result = false;
		String[] sql = new String[6];
		sql[0] = "select count(*) as Num from XFIT_Day_Summary";
		sql[1] = "select count(*) as Num from XFIT_Per_Running";
		sql[2] = "select count(*) as Num from XFIT_Speed_Detail";
		sql[3] = "select count(*) as Num from XFIT_Tracking_Detail";
		sql[4] = "select count(*) as Num from MonthWeekYearReport";
		sql[5] = "select count(*) as Num from XFIT_User_Info";
		DBServices ds = new DBServices();
		for (int i = 0; i < sql.length; i++)
		{
			ArrayList<Dictionary> tempRe = ds.ExecuteReader1(sql[i],context);
			if (tempRe.isEmpty() == false)
			{
				if (!tempRe.get(0).get("Num").toString().equals("0"))
				{
					result = true;
					break;
				}
			}
		}
		return result;
	}
	
	
	/**
	 * @param context
	 * @param UserId 用户ID
	 * @return
	 */
	public Cursor get20table(Context context,int UserId)
	{
		DBServices ds = new DBServices();
		//ds.insertMountData(context);
		String sql = "select ID as _id,RunningID,StartTime,SportTime/60 as SportTime,Distance from XFIT_Per_Running where UserID=" + String.valueOf(UserId) + " and isRunning like '%Y%' order by StartTime desc limit 20";
		Cursor result = ds.get20running(sql, context);
		return result;
	}
	public Cursor get20tableSpecific(Context context,int UserId, Date selDate)
	{
		DBServices ds = new DBServices();
		java.sql.Date selSqlDate = new java.sql.Date(selDate.getTime());
		String sql = "select * from (select ID as _id,RunningID,StartTime,SportTime/60 as SportTime,Distance from XFIT_Per_Running where UserID=" + String.valueOf(UserId) + " and isRunning like '%Y%' and StartTime between '2008-01-01 00:00:00' and '"+selSqlDate.toString()+" 23:59:59') order by StartTime desc limit 20";
		Cursor result = ds.get20running(sql, context);
		return result;
	}
	public boolean deleteOneReport(int reportID, Context context)
	{
		boolean result = false;
		DBServices ds = new DBServices();
		long tempp = ds.ExecuteDeleteSingle(reportID, context, "MonthWeekYearReport");
		if (tempp == 1)
		{
			result = true;
		}
		return result;
	}
	
	/**
	 * @param context
	 * @param UserId
	 * @param id  (RunningId)
	 * @return "SportTime", "Distance"
	 */
	public Hashtable<String, String> get20tableElementInfo(Context context, int UserId, int id)
	{
		Hashtable<String, String> result = new Hashtable<String, String>();
		ArrayList<Dictionary> tempResultt = new ArrayList<Dictionary>();
		String sql = "select SportTime/60 as SportTime,Distance from XFIT_Per_Running where RunningID="+String.valueOf(id)+" and UserID=" + String.valueOf(UserId);
		DBServices ds = new DBServices();
		tempResultt = ds.ExecuteReader1(sql, context);
		if (tempResultt.size() != 0)
		{
			result.put("SportTime", tempResultt.get(0).get("SportTime").toString());
			result.put("Distance", tempResultt.get(0).get("Distance").toString());
		}
		else
		{
			result.put("SportTime", "");
			result.put("Distance", "");
		}
		return result;
	}
	
	public ContentValues packagingTrackingData(Date Track_Date, int UserID, int Strength, char Caluculated_Flag, Date Start_DateTime, String Client_VerNumber, double Calorie)
	{
		ContentValues cValue = new ContentValues();
		java.sql.Timestamp TrackD=new java.sql.Timestamp(Track_Date.getTime());
		cValue.put("Track_Date", TrackD.toString());
		java.sql.Timestamp StartD = new java.sql.Timestamp(Start_DateTime.getTime());
		cValue.put("Start_DateTime",  StartD.toString());
		cValue.put("Client_VerNumber", Client_VerNumber);
		cValue.put("UserID", String.valueOf(UserID));
		cValue.put("Calculated_Flag", String.valueOf(Caluculated_Flag)); 
		cValue.put("Strength", String.valueOf(Strength));
		cValue.put("Calorie", String.valueOf(Calorie));
		return cValue;
	}
	
	public ContentValues packagingSpeedData(int SpeedTraceID, int UserID, int RunningID, Date TrackDate, double TimeSpan, double AverageSpeed)
	{
		ContentValues cValue = new ContentValues();
		java.sql.Timestamp TrackD=new java.sql.Timestamp(TrackDate.getTime());
		cValue.put("SpeedTraceID", String.valueOf(SpeedTraceID));
		cValue.put("UserID", String.valueOf(UserID));
		cValue.put("RunningID", String.valueOf(RunningID));
		cValue.put("TrackDate", TrackD.toString());
		cValue.put("TimeSpan", String.valueOf(TimeSpan)); 
		cValue.put("AverageSpeed",String.valueOf(AverageSpeed));
		return cValue;
	}
	
	public ContentValues packagingDaySumData(int DaySummaryID, Date SummaryDate, int UserID, double SportTime, double Calorie, double Distance)
	{
		ContentValues cValue = new ContentValues();
		cValue.put("DaySummaryID", String.valueOf(DaySummaryID));
		java.sql.Timestamp TrackD=new java.sql.Timestamp(SummaryDate.getTime());
		cValue.put("SummaryDate", TrackD.toString());
		cValue.put("UserID", String.valueOf(UserID));
		cValue.put("SportTime", String.valueOf(SportTime));
		cValue.put("Calorie", String.valueOf(Calorie));
		cValue.put("Distance", String.valueOf(Distance));
		return cValue;
	}
	
	public ContentValues packagingTrackingDataString(String Track_Date, String TimeSpan,String UserID,String Steps, String Strength, String Caluculated_Flag, String Start_DateTime, String Client_VerNumber, String Calorie) throws ParseException
	{
		ContentValues cValue = new ContentValues();
		DateFormat from_type1;
		DateFormat from_type2;
		if (Track_Date.length() == 17)
			from_type1 = new SimpleDateFormat("yyyy-M-d H:mm:ss");
		else
			from_type1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if (Start_DateTime.length() == 17)
			from_type2 = new SimpleDateFormat("yyyy-M-d H:mm:ss");
		else
			from_type2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date tdtemp = from_type1.parse(Track_Date);
		java.sql.Timestamp TrackD=new java.sql.Timestamp(tdtemp.getTime());
		
		Date sdtemp = from_type2.parse(Start_DateTime);
		java.sql.Timestamp StartD=new java.sql.Timestamp(sdtemp.getTime());
		
		cValue.put("Track_Date", TrackD.toString());
		cValue.put("TimeSpan", TimeSpan);
		cValue.put("Steps", Steps);
		cValue.put("Start_DateTime",  StartD.toString());
		cValue.put("Client_VerNumber", Client_VerNumber);
		cValue.put("UserID", String.valueOf(UserID));
		cValue.put("Calculated_Flag", String.valueOf(Caluculated_Flag)); 
		cValue.put("Strength", String.valueOf(Strength));
		cValue.put("Calorie", String.valueOf(Calorie));
		return cValue;
	}
	
	public ContentValues packagingDaySumDataString(String DaySummaryID, String SummaryDate, String UserID, String SportTime, String Calorie, String Distance) throws ParseException
	{
		ContentValues cValue = new ContentValues();
		cValue.put("DaySummaryID", DaySummaryID);
//		DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Date tempSumDate = from_type.parse(SummaryDate);
//		java.sql.Timestamp TrackD=new java.sql.Timestamp(tempSumDate.getTime());
		
		DateFormat from_type1;
		if (SummaryDate.length() == 17)
			from_type1 = new SimpleDateFormat("yyyy-M-d H:mm:ss");
		else
			from_type1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date sdtemp = from_type1.parse(SummaryDate);
		java.sql.Timestamp SumD=new java.sql.Timestamp(sdtemp.getTime());
		
		cValue.put("SummaryDate", SumD.toString());
		cValue.put("UserID", UserID);
		cValue.put("SportTime", SportTime);
		cValue.put("Calorie", Calorie);
		cValue.put("Distance", Distance);
		return cValue;
	}
	
	public ContentValues packagingSpeedDataString(String SpeedTraceID, String UserID, String RunningID, String TrackDate, String TimeSpan, String AverageSpeed) throws ParseException
	{
		DateFormat from_type1;
		if (TrackDate.length() == 17)
			from_type1 = new SimpleDateFormat("yyyy-M-d H:mm:ss");
		else
			from_type1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date tdtemp = from_type1.parse(TrackDate);
		java.sql.Timestamp TrackD=new java.sql.Timestamp(tdtemp.getTime());
		
		ContentValues cValue = new ContentValues();
		cValue.put("SpeedTraceID", String.valueOf(SpeedTraceID));
		cValue.put("UserID", String.valueOf(UserID));
		cValue.put("RunningID", String.valueOf(RunningID));
		cValue.put("TrackDate", TrackD.toString());
		cValue.put("TimeSpan", String.valueOf(TimeSpan)); 
		cValue.put("AverageSpeed",String.valueOf(AverageSpeed));
		return cValue;
	}
	
	public ContentValues packagingStepsString(int UserID, int TYear, int TMonth, int TDay, int NumOfTwoHours, int NumOf30s, int Steps)
	{
		ContentValues result = new ContentValues();
		result.put("UserID", String.valueOf(UserID));
		result.put("TYear", String.valueOf(TYear));
		result.put("TMonth", String.valueOf(TMonth));
		result.put("TDay", String.valueOf(TDay));
		result.put("NumOfTwoHours", String.valueOf(NumOfTwoHours));
		result.put("NumOf30s", String.valueOf(NumOf30s)); 
		result.put("Steps",String.valueOf(Steps));
		result.put("TimeD", String.valueOf(TYear) + String.valueOf(TMonth) + String.valueOf(TDay) + String.valueOf(NumOf30s));
		return result;
	}
	
	private String getTimeD(Context context)
	{
		String result = "";
		String sql = "select TimeD from UpdateStatus where TableName='Steps_Detail'";
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		result = tempRe.get(0).get("TimeD").toString();
		return result;
	}
	
	public String wrapUploadData(String UserID, Context context)
	{
		String result = "";
		String sql = "select TYear,TMonth,TDay,NumOfTwoHours,NumOf30s,TimeD,Steps from Steps_Detail where UserID=" + UserID + " group by TimeD";
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		for (int i = 0; i < tempRe.size(); i++)
		{
			int TYear = Integer.parseInt(tempRe.get(i).get("TYear").toString());
			int TMonth = Integer.parseInt(tempRe.get(i).get("TMonth").toString());
			int TDay = Integer.parseInt(tempRe.get(i).get("TDay").toString());
			int NumOfTwoHours = Integer.parseInt(tempRe.get(i).get("NumOfTwoHours").toString());
			int NumOf30s = Integer.parseInt(tempRe.get(i).get("NumOf30s").toString());
			int Steps = Integer.parseInt(tempRe.get(i).get("Steps").toString());
			String timeDD = tempRe.get(i).get("TimeD").toString();

			String tYear = Integer.toHexString(TYear);
			 while (tYear.length() < 4) {
				 tYear = "0" + tYear;
		        }
			String tMonth = Integer.toHexString(TMonth);
			 while (tMonth.length() < 4) {
				 tMonth = "0" + tMonth;
		        }
			String tDay = Integer.toHexString(TDay);
			 while (tDay.length() < 4) {
				 tDay = "0" + tDay;
		        }
			String numOfTwoHours = Integer.toHexString(NumOfTwoHours);
			 while (numOfTwoHours.length() < 4) {
				 numOfTwoHours = "0" + numOfTwoHours;
		        }
			String numOf30s = Integer.toHexString(NumOf30s);
			 while (numOf30s.length() < 4) {
				 numOf30s = "0" + numOf30s;
		        }
			String steps = Integer.toHexString(Steps);
			 while (steps.length() < 4) {
				 steps = "0" + steps;
		        }
			 
			if (i > 0 && !tempRe.get(i).get("TimeD").toString().equals(tempRe.get(i-1).get("TimeD").toString()))
			{
				result = result.concat("00FF;" + tYear + ";" + tMonth + ";" + numOfTwoHours + ";" + tDay + "|");
				result = result.concat(numOf30s + ";" + steps + ";0000;0000" + "|");
			}
			else if (i == 0)
			{
				result = result.concat("00FF;" + tYear + ";" + tMonth + ";" + numOfTwoHours + ";" + tDay + "|");
				result = result.concat(numOf30s + ";" + steps + ";0000;0000" + "|");
			}
			else
			{
				result = result.concat(numOf30s + ";" + steps + ";0000;0000" + "|");
			}
			
//			if (i == tempRe.size()-1)//若是此批次的最后一行数据，将此行的TimeD更新到UpdateStatus保存起来，以备下批数据第一行数据时比对所用
//			{
//				String sqlU = "update UpdateStatus set TimeD='"+timeDD+"' where TableName='Steps_Detail'";
//				ds.executeUpdate(sqlU, context);
//			}
		}
		return result;
	}
	
	
	public boolean insertStepsSingle(Context context, int UserID, int Steps, Date dt)
	{
		boolean result = false;
		String tName = "Steps_Detail";
		int hour = dt.getHours();
		int minute = dt.getMinutes();
		int second = dt.getSeconds();
		int TYear = dt.getYear() + 1900;
		int TMonth = dt.getMonth() + 1;
		int TDay = dt.getDate();
		int NumOfTwoHours = hour / 2 + 1;//1:0~2;2:2~4
		int NumOf30s = 0;
		if (hour % 2 == 0)//if hour is even.
			NumOf30s = (60 * minute + second) / 30 + 1;
		else
			NumOf30s = (3600 + 60 * minute + second) / 30 + 1;
		
		ContentValues cValue = new ContentValues();
		cValue =  packagingStepsString(UserID, TYear, TMonth, TDay, NumOfTwoHours, NumOf30s, Steps);
		long tempRe = 0;
		DBServices dbs = new DBServices();
		tempRe = dbs.ExecuteInsertSingle(cValue, context, tName);
		if (tempRe != -1)
		{
			result = true;
		}
		else
		{
			result = false;
		}
		return result;
	}
	
	public ContentValues translateDate(Date dt)
	{
		ContentValues result = new ContentValues();
		int hour = dt.getHours();
		int minute = dt.getMinutes();
		int second = dt.getSeconds();
		int year = dt.getYear() + 1900;
		int month = dt.getMonth();
		int day = dt.getDate();
		int numOfTwoHours = hour / 2 + 1;
		int NumOf30s = 0;
		if (hour % 2 == 1)
			NumOf30s = (60 * minute + second) / 30;
		else
			NumOf30s = (3600 + 60 * minute + second) / 30;
		return result;
	}
	
	public ContentValues packagingPerRunningString(String RunningID,String UserID, String StartTime, String EndTime, String SportTime, String Calorie, String Distance, String IsRunning) throws ParseException
	{
		DateFormat from_type1;
		DateFormat from_type2;
		if (StartTime.length() == 17)
			from_type1 = new SimpleDateFormat("yyyy-M-d H:mm:ss");
		else
			from_type1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if (EndTime.length() == 17)
			from_type2 = new SimpleDateFormat("yyyy-M-d H:mm:ss");
		else
			from_type2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date tdtemp = from_type1.parse(StartTime);
		java.sql.Timestamp StartD=new java.sql.Timestamp(tdtemp.getTime());
		
		Date sdtemp = from_type2.parse(EndTime);
		java.sql.Timestamp EndD=new java.sql.Timestamp(sdtemp.getTime());
		ContentValues cValue = new ContentValues();
		cValue.put("RunningID", RunningID);
		cValue.put("UserID", UserID);
		cValue.put("StartTime", StartD.toString());
		cValue.put("EndTime", EndD.toString());
		cValue.put("SportTime", SportTime);
		cValue.put("Calorie", Calorie);
		cValue.put("Distance", Distance);
		cValue.put("IsRunning", IsRunning.trim());
		return cValue;
	}
	
	
	public long testDaySumData(Context context)
	{
		ArrayList<ContentValues> result = new ArrayList<ContentValues>();
		int year = 113;
		int month = 2;
		int day = 1;
		int hour = 11;
		int minutes = 1;
		int seconds = 0;
		
		int DaySummaryID = 1;
		int UserID = 91;
		double SportTime = 10.0;
		double Calorie = 2.0;
		double Distance = 5.0;
		
		for (int i = 0; i < 25; i++)
		{
			Date SummaryDate = new Date(year,month,day);
			ContentValues tempC = new ContentValues();
			tempC = packagingDaySumData(DaySummaryID, SummaryDate, UserID, SportTime, Calorie, Distance);
			day++;
			DaySummaryID++;
			SportTime += 0.2;
			Calorie += 0.12;
			Distance += 1.3;
			result.add(tempC);
		}
		
		String tName = "XFIT_Day_Summary";
		DBServices dbs = new DBServices();
		long num = dbs.ExecuteInsertMultiple(result, context, tName);
		return num;
	}
	
	public long testSpeedData(Context context)
	{
		ArrayList<ContentValues> result = new ArrayList<ContentValues>();
		int year = 113;
		int month = 1;
		int day = 4;
		int hour = 11;
		int minutes = 1;
		int seconds = 0;
		Date TrackDate = new Date(year,month,day);
		int SpeedTraceID = 0;
		int UserID = 91;
		int RunningID = 9;
		double TimeSpan = 30.0;
		double AverageSpeed = 0.7;
		for (int i = 0; i < 59; i++)
		{
			TrackDate.setHours(hour);
			TrackDate.setMinutes(minutes);
			TrackDate.setSeconds(seconds);
			seconds = (seconds + 30) % 60;
			minutes++;
			AverageSpeed = AverageSpeed + 0.1;
			ContentValues tempC = new ContentValues();
			tempC = packagingSpeedData(SpeedTraceID, UserID, RunningID, TrackDate, TimeSpan, AverageSpeed);
			result.add(tempC);
		}
		
		String tName = "XFIT_Speed_Detail";
		DBServices dbs = new DBServices();
		long num = dbs.ExecuteInsertMultiple(result, context, tName);
		return num;
	}
	
	public long testTrackingData(Context context)
	{
		ArrayList<ContentValues> result = new ArrayList<ContentValues>();
		int UserID = 91;
		int Strength = 9;
		char Caluculated_Flag = 'a';
		int year = 113;
		int month = 1;
		int day = 4;
		int hour = 11;
		int minutes = 1;
		int seconds = 0;
		Date Start_DateTime = new Date(year,month,day);
		Date Track_Date = new Date(year,month,day);
		String Client_VerNumber = "1";
		double Calorie = 2.0;
		for (int i = 0; i < 59; i++)
		{
			Track_Date.setHours(hour);
			Track_Date.setMinutes(minutes);
			Track_Date.setSeconds(seconds);
			seconds = (seconds + 30) % 60;
			minutes++;
			Calorie = Calorie + 0.1;
			ContentValues tempC = new ContentValues();
			tempC = packagingTrackingData(Track_Date, UserID, Strength, Caluculated_Flag, Start_DateTime, Client_VerNumber, Calorie);
			result.add(tempC);
		}
		long num = tracking_insertMultiple(context, result);
		return num;
	}
	
	public boolean tracking_insertSingle(Context context,Date Track_Date, int UserID, int Strength, char Caluculated_Flag, Date Start_DateTime, String Client_VerNumber, Double Calorie)
	{
		boolean result = false;
		String tName = "XFIT_Tracking_Detail";
		ContentValues cValue = new ContentValues();
		cValue =  packagingTrackingData(Track_Date, UserID, Strength, Caluculated_Flag, Start_DateTime, Client_VerNumber, Calorie);
		long tempRe = 0;
		DBServices dbs = new DBServices();
		tempRe = dbs.ExecuteInsertSingle(cValue, context, tName);
		if (tempRe != -1)
		{
			result = true;
		}
		else
		{
			result = false;
		}
		return result;
	}
	
	/**
	 * @param context
	 * @param data 批量插入数据以ContentValues为类型的泛型ArrayList
	 * @param tName 插入的表名
	 * @return 插入的行数
	 */
	public long tracking_insertMultiple(Context context, ArrayList<ContentValues> data)
	{
		String tName = "XFIT_Tracking_Detail";
		long result = 0;
		DBServices dbs = new DBServices();
		result = dbs.ExecuteInsertMultiple(data, context, tName);
		return result;
	}
	
	
	
	/**
	 * @param userID
	 * @param context
	 * @param runningID
	 * @return 1：一次跑步的timebucket 2：一次跑步的花的时间 3：一次跑步跑得距离 4：一次跑步的平均速度 5：一次跑步30s为间隔的y轴数据
	 * @throws ParseException 
	 */
	public Hashtable get20tableElement(int userID, Context context,int runningID) throws ParseException
	{
		Hashtable result = new Hashtable();
		double adjustmentData = getAdjustmentData(userID, context);
		String sql1 = "select StartTime,EndTime,Distance/SportTime as Avgspeed from XFIT_Per_Running where UserID="+String.valueOf(userID)+" and RunningID=" + String.valueOf(runningID);
		String sql2 = "select AverageSpeed from XFIT_Speed_Detail where UserID="+String.valueOf(userID)+" and RunningID=" + String.valueOf(runningID)+" order by TrackDate";
		
		DBServices ds = new DBServices();
		ArrayList<Dictionary> perRunning = new ArrayList<Dictionary>();
		ArrayList<Dictionary> per30 = new ArrayList<Dictionary>();
		
		perRunning = ds.ExecuteReader1(sql1, context);
		per30 = ds.ExecuteReader1(sql2, context);
		DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (perRunning.size() != 0)
		{
			Date tempS = from_type.parse(perRunning.get(0).get("StartTime").toString());
			Date tempE = from_type.parse(perRunning.get(0).get("EndTime").toString());
			double avgSpeed = Double.parseDouble(perRunning.get(0).get("Avgspeed").toString())*adjustmentData;
			result.put("startTime", tempS);
			result.put("endTime", tempE);
			result.put("timeBucket", perRunning.get(0).get("StartTime").toString() + "~" + perRunning.get(0).get("EndTime").toString());
			//jiting 临时修改
			//result.put("avgSpeed", avgSpeed);
			result.put("iTimeType", 0);
			result.put("iShowType", 3);
		}
		
		if (per30.size() != 0)
		{
			double[] tempRe = new double[per30.size()];
			for (int i = 0; i < per30.size(); i++)
			{
				tempRe[i] = Double.parseDouble(per30.get(i).get("AverageSpeed").toString())*adjustmentData;
			}
			result.put("yArray", tempRe);
		}
		else
		{
			double[] tempRe = new double[1];
			tempRe[0] = 0;
			result.put("yArray", tempRe);
		}
		
		return result;
	}
	
	
	private long deleteAndDownloadDaySumOne(String UserID, String selDate, Context context, String sessionId, String client_vernumber, DBServices ds)
	{
		long result = 0;
		selDate = selDate.substring(0, 10);
		String startTime = selDate + " 00:00:00";
		String endTime = selDate + " 23:59:59";
		DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date tempS = new Date();
		Date tempE = new Date();
		try {
			tempS = from_type.parse(startTime);
			tempE = from_type.parse(endTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			ArrayList<ContentValues> tempResult = this.downloadData(sessionId, tempS, tempE, client_vernumber, 0);
			if (tempResult.size() == 0)
			{
				return result;
			}
			else
			{
				String sql22 = "delete from XFIT_Day_Summary where SummaryDate between '" + startTime + "' and '" + endTime + "' and UserID=" + UserID;
				ds = new DBServices();
				ds.executeDelete(sql22, context);

				String tName = "XFIT_Day_Summary";
				DBServices dbs = new DBServices();
				result = dbs.ExecuteInsertMultiple(tempResult, context, tName);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * @param UserID
	 * @param iShowType 所要显示的类型 0时间，1距离，2卡路里，3速度
	 * @param iTimeType 所需显示的时间类型 0按日，1按周，2按月，3按年
	 * @param selDate "yyyy-MM-dd"或"yyyy-MM-dd HH:mm:ss"
	 * @param context
	 * @return 日的总结性文字
	 */
	public String getDaySummaryComments(String UserID, int iTimeType, String client_vernumber, String selDate, int iShowType, Context context)
	{
		String result = "";
		String sql = "";
		selDate = selDate.substring(0, 10);
		String startTime = selDate + " 00:00:00";
		String endTime = selDate + " 23:59:59";
		DBServices ds = new DBServices();
		DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date tempS = new Date();
		Date tempE = new Date();
		try {
			tempS = from_type.parse(startTime);
			tempE = from_type.parse(endTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (iTimeType == 0)
		{					
//			try {
//				ArrayList<ContentValues> tempResult = this.downloadData(sessionId, tempS, tempE, client_vernumber, 0);
//				if (tempResult.size() == 0)
//				{
//					return "跑步距离为0公里";
//				}
//				else
//				{
//					String sql22 = "delete from XFIT_Day_Summary where SummaryDate between '" + startTime + "' and '" + endTime + "' and UserID=" + UserID;
//					ds = new DBServices();
//					ds.executeDelete(sql22, context);
//
//					String tName = "XFIT_Day_Summary";
//					DBServices dbs = new DBServices();
//					long numm = dbs.ExecuteInsertMultiple(tempResult, context, tName);
//				}
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			String oneday = getNianYueRi(tempS);
			if (iShowType == 2)
			{

				sql = "select Calorie from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID=" + UserID;
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				String calorie = "";
				if (tempRe.size() >= 1)
				{
					calorie = tempRe.get(0).get("Calorie").toString();
				}
				else
				{
					calorie = "0";
				}
				result = "我于"+oneday+"运动消耗卡路里"+calorie+"千卡";
			}
			else
			{
				sql = "select SportTime/60 as SportTime,Distance from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID=" + UserID;
				//sql = "select SportTime/60 as SportTime,Distance from XFIT_Day_Summary where SummaryDate='"+startTime+"' and UserID=" + UserID;
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				String sporttime = "";
				String distance = "";
				if (tempRe.size() >= 1)
				{
					sporttime = tempRe.get(0).get("SportTime").toString();
					distance = tempRe.get(0).get("Distance").toString();
				}
				else
				{
					sporttime = "0";
					distance = "0";
				}
				result = "我于"+oneday+"完成运动"+distance+"公里耗时"+sporttime+"分钟";
			}
		}
		return result;
	}
	
	private String getNianYueRi(Date tempS)
	{
		String result = String.valueOf(tempS.getYear() + 1900) + "年" + String.valueOf(tempS.getMonth() + 1) + "月" + String.valueOf(tempS.getDate()) + "日";
		return result;
	}

	/**
	 * @param UserID
	 * @param iShowType 所要显示的类型 0时间，1距离，2卡路里，3速度
	 * @param iTimeType 所需显示的时间类型 0按日，1按周，2按月，3按年
	 * @param startTime 格式为 "yyyy-MM-dd HH:mm:ss"
	 * @param endTime 格式为 "yyyy-MM-dd HH:mm:ss"
	 * @param context
	 * @return 微博分享文字
	 */
	public String getWeiboInfo(String UserID, String sessionId, int iTimeType, String client_vernumber, String startTime, String endTime, int iShowType, Context context, String runningid)
	{
		String result = "";
		String sql = "";
		startTime = startTime.substring(0, 19);
		endTime = endTime.substring(0, 19);
		DBServices ds = new DBServices();
		DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date tempS = new Date();
		Date tempE = new Date();
		try {
			tempS = from_type.parse(startTime);
			tempE = from_type.parse(endTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		if (runningid != "" && runningid.length() > 0)
		{
			Hashtable running = this.get20tableElementInfo(context, Integer.parseInt(UserID), Integer.parseInt(runningid));
			String sporttime = running.get("SportTime").toString();
			String distance = running.get("Distance").toString();
			result = "此次运动的总时间为：" + sporttime +"分钟，运动距离为：" + distance + "公里，快来加入我们吧！";
		}
		else
		{
		
			if (iTimeType == 0)
			{					
				try {
					ArrayList<ContentValues> tempResult = this.downloadData(sessionId, tempS, tempE, client_vernumber, 0);
					if (tempResult.size() == 0)
					{
						return "跑步距离为0公里";
					}
					else
					{
						String sql22 = "delete from XFIT_Day_Summary where SummaryDate between '" + startTime + "' and '" + endTime + "' and UserID=" + UserID;
						ds = new DBServices();
						ds.executeDelete(sql22, context);

						String tName = "XFIT_Day_Summary";
						DBServices dbs = new DBServices();
						long numm = dbs.ExecuteInsertMultiple(tempResult, context, tName);
						Log.i("", "");
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String oneday = getNianYueRi(tempS);
				if (iShowType == 2)
				{

					sql = "select Calorie from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID=" + UserID;
					ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					tempRe = ds.ExecuteReader1(sql,context);
					String calorie = "";
					if (tempRe.size() >= 1)
					{
						calorie = tempRe.get(0).get("Calorie").toString();
					}
					else
					{
						calorie = "0";
					}
					result = "我于"+oneday+"运动消耗卡路里"+calorie+"千卡，我把消耗的细节分享出来，我们大家一起都来运动吧。";
				}
				else
				{
					sql = "select SportTime/60 as SportTime,Distance from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID=" + UserID;
					ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					tempRe = ds.ExecuteReader1(sql,context);
					String sporttime = "";
					String distance = "";
					if (tempRe.size() >= 1)
					{
						sporttime = tempRe.get(0).get("SportTime").toString();
						distance = tempRe.get(0).get("Distance").toString();
					}
					else
					{
						sporttime = "0";
						distance = "0";
					}
					result = "我于"+oneday+"完成运动"+distance+"公里耗时"+sporttime+"分钟，我把消耗的细节分享出来，我们大家一起都来运动吧。";
				}
			}
			else if (iTimeType == 1 || iTimeType == 2)
			{
				if (iShowType == 0)
				{
					sql = "select SportTime/60 as SportTime,SummaryDate from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID="+UserID+" order by SportTime";
					ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					tempRe = ds.ExecuteReader1(sql,context);
					String maxSportTime = "";
					String minSportTime = "";

					if (tempRe.size() >= 1)
					{
						maxSportTime = tempRe.get(0).get("SportTime").toString();
						minSportTime = tempRe.get(tempRe.size() - 1).get("SportTime").toString();
					}
					else
					{
						maxSportTime = "0";
						minSportTime = "0";
					}

					String maxDate = tempRe.get(0).get("SummaryDate").toString();
					String minDate = tempRe.get(tempRe.size() - 1).get("SummaryDate").toString();

					result = "我于"+minDate+"累积运动时间最多，达到"+minSportTime+"分钟，"+maxDate+"日运动最少，有"+maxSportTime+"分钟，我们大家一起也都来运动吧。";
				}
				else if (iShowType == 1)
				{
					sql = "select Distance,SummaryDate from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID="+UserID+" order by Distance";
					ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					tempRe = ds.ExecuteReader1(sql,context);
					String maxDistance = "";
					String minDistance = "";

					if (tempRe.size() >= 1)
					{
						minDistance = tempRe.get(0).get("Distance").toString();
						maxDistance = tempRe.get(tempRe.size() - 1).get("Distance").toString();
					}
					else
					{
						maxDistance = "0";
						minDistance = "0";
					}

					String minDate = tempRe.get(0).get("SummaryDate").toString();
					String maxDate = tempRe.get(tempRe.size() - 1).get("SummaryDate").toString();

					result = "我于"+maxDate+"累积运动距离最多，达到"+maxDistance+"公里，"+minDate+"运动最少，有"+minDistance+"公里，我们大家一起也都来运动吧。";
				}
				else if (iShowType == 2)
				{
					sql = "select Calorie,SummaryDate from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID="+UserID+" order by Calorie";
					ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					tempRe = ds.ExecuteReader1(sql,context);
					String maxCalorie = "";
					String minCalorie = "";

					if (tempRe.size() >= 1)
					{
						minCalorie = tempRe.get(0).get("Calorie").toString();
						maxCalorie = tempRe.get(tempRe.size() - 1).get("Calorie").toString();
					}
					else
					{
						maxCalorie = "0";
						minCalorie = "0";
					}

					String minDate = tempRe.get(0).get("SummaryDate").toString();
					String maxDate = tempRe.get(tempRe.size() - 1).get("SummaryDate").toString();

					result = "我于"+maxDate+"运动最多，消耗"+maxCalorie+"千卡，"+minDate+"运动最少，消耗"+minCalorie+"千卡，少吃多动保健康，大家都来加入吧。";
				}
				else if (iShowType == 3)
				{
					//				String running = "";
					//				String sql1 = "select count(*) as num from XFIT_Per_Running where StartTime between '"+startTime+"' and '"+endTime+"' and UserID=7";
					//				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					//				tempRe = ds.ExecuteReader1(sql1,context);
					//				if (tempRe.size() >= 1)
					//				{
					//					running = tempRe.get(0).get("num").toString();
					//				}
					//				else
					//				{
					//					running = "0";
					//				}
					//				
					//				String sql2 = "";

					sql = "select Distance/(SportTime/3600) as speed,SummaryDate from XFIT_Day_Summary where SummaryDate between '"+startTime+"' and '"+endTime+"' and UserID="+UserID+" order by speed";
					ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
					tempRe = ds.ExecuteReader1(sql,context);
					String maxspeed = "";
					String minspeed = "";

					if (tempRe.size() >= 1)
					{
						minspeed = tempRe.get(0).get("speed").toString();
						maxspeed = tempRe.get(tempRe.size() - 1).get("speed").toString();
					}
					else
					{
						maxspeed = "0";
						minspeed = "0";
					}

					String minDate = tempRe.get(0).get("SummaryDate").toString();
					String maxDate = tempRe.get(tempRe.size() - 1).get("SummaryDate").toString();

					result = "我于"+maxDate+"速度最快，为"+maxspeed+"公里/小时，"+minDate+"运动最慢，速度为"+minspeed+"公里/小时，少吃多动保健康，大家都来加入吧。";
				}
			}
			else if (iTimeType == 3)
			{
				result = "少吃多动保健康，大家都来加入吧。";
			}
		}
		
		return result;
	}
	
	private Hashtable getOneReport(String UserID, int iTimeType, String startTime, String endTime, int iShowType, Context context, double adjustData, DBServices ds, int isStore, int SpeedInStoring) throws ParseException
	{
		Hashtable result = new Hashtable();
		result.put("iTimeType", iTimeType);
		result.put("iShowType", iShowType);
		String timeBucket = "";
		if(startTime.length() > 10)
		{
			startTime = startTime.substring(0, 19);
		}
		if(endTime.length() > 10)
		{
			endTime = endTime.substring(0, 19);
		}
		double[] values;
		timeBucket = startTime + "到" + endTime;
        result.put("timeBucket", timeBucket);
        DateFormat from_type;
        if (isStore == 1)//getReports调用，
        {	
//        	if (SpeedInStoring != 1)
//        	{
//        	from_type = new SimpleDateFormat("yyyy-MM-dd");
//        	
//            //DaoChartInfo->java.sql.date
//            
//    			startTime += " 00:00:00";
//    			endTime += " 23:59:59.999";
//        	}
//        	else
//        	{
//        		from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        	}
    			from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        else
        {
        	from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        Date tempS = from_type.parse(startTime);
        Date tempE = from_type.parse(endTime);
        

        
		if (iShowType == 2)//卡路里
		{
			if (iTimeType == 1)//按周
			{
				String sql = "SELECT Calorie,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Calorie").toString())*adjustData;
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 2)//按月
			{

				int dayNum = getTheDayNumOfMonth(tempS.getYear(),tempS.getMonth());//取日期所在月份的天数
				String sql = "SELECT Calorie,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Calorie").toString())*adjustData;
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 3)//按年
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(tempS.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					
					yArray[i] = getMonthSum(temp, Integer.parseInt(UserID), context,iShowType)*adjustData;
				}
				//result.put("timeBucket", String.valueOf(tempS.getYear()) + "�?月~12�?);
				result.put("yArray", yArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 0)//按日
			{
//				double[] yArray = new double[24];
//				Date temp = new Date(selDate.getTime());
//				for (int i = 0; i < 24; i++)
//				{
//					temp.setHours(i);
//					temp.setMinutes(1);
//					temp.setSeconds(1);
//					
//					yArray[i] = getHourSum(temp, UserID, context, iShowType);
//				}
//				
//				result.put("timeBucket", selDate.toString());
//				result.put("yArray", yArray);

				double[] yArray = oneDaySummary(startTime,endTime,context,"Calorie",Integer.parseInt(UserID));
				result.put("yArray", yArray);
				tempS.setHours(0);
				tempS.setMinutes(0);
				tempS.setSeconds(0);
				tempE.setHours(23);
				tempE.setMinutes(59);
				tempE.setSeconds(59);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
		}
		else if (iShowType == 0)
		{	
			if (iTimeType == 1)
			{
				String sql = "SELECT SportTime,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("SportTime").toString());
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 2)
			{
				int dayNum = getTheDayNumOfMonth(tempS.getYear(),tempS.getMonth());//取日期所在月份的天数
				String sql = "SELECT SportTime,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("SportTime").toString());
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 3)
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(tempS.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					
					yArray[i] = getMonthSum(temp, Integer.parseInt(UserID), context,iShowType);
				}
				//result.put("timeBucket", String.valueOf(tempS.getYear()) + "�?月~12�?);
				result.put("yArray", yArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 0)
			{
				double[] yArray = oneDaySummary(startTime,endTime,context,"SportTime",Integer.parseInt(UserID));
				result.put("yArray", yArray);
				tempS.setHours(0);
				tempS.setMinutes(0);
				tempS.setSeconds(0);
				tempE.setHours(23);
				tempE.setMinutes(59);
				tempE.setSeconds(59);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
		}
		else if (iShowType == 1)//按距离
		{
			if (iTimeType == 1)//按周
			{
				String sql = "SELECT Distance,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				
				double[] yArray = new double[tempRe.size()];
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData;
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
				
			}
			else if (iTimeType == 2)//按月
			{
				String sql = "SELECT Distance,SummaryDate FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
				
				int dayNum = getTheDayNumOfMonth(tempS.getYear(),tempS.getMonth());//取日期所在月份的天数
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData;
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 3)//按年
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(tempS.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					
					yArray[i] = getMonthSum(temp, Integer.parseInt(UserID), context,iShowType)*adjustData;
				}
				//result.put("timeBucket", String.valueOf(tempS.getYear()) + "�?月~12�?);
				result.put("yArray", yArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 0)//按日
			{
//				double[] yArray = new double[24];
//				Date temp = new Date(selDate.getTime());
//				for (int i = 0; i < 24; i++)
//				{
//					temp.setHours(i);
//					temp.setMinutes(1);
//					temp.setSeconds(1);
//					
//					yArray[i] = getHourSum(temp, UserID, context, iShowType);
//				}
//				
//				result.put("timeBucket", selDate.toString());
//				result.put("yArray", yArray);
//				result.put("startTime", tempS);
//				result.put("endTime", tempE);
				double[] yArray = oneDaySummary(startTime,endTime,context,"Distance",Integer.parseInt(UserID));
				result.put("yArray", yArray);
				tempS.setHours(0);
				tempS.setMinutes(0);
				tempS.setSeconds(0);
				tempE.setHours(23);
				tempE.setMinutes(59);
				tempE.setSeconds(59);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
				
			}
		}
		else if (iShowType == 3)//平均速度
		{
			if (iTimeType == 1)//按周
			{
				
				String sql = "SELECT Distance,SummaryDate,SportTime FROM XFIT_Day_Summary WHERE UserID="+String.valueOf(UserID)+" AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];
//				double[] xArray = new double[tempRe.size()];
//				
//				for (int i = 0; i < tempRe.size(); i++)
//				{
//					double tempCal = (Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData)/Double.parseDouble(tempRe.get(i).get("SportTime").toString());
//					double tempSumDate = Double.parseDouble(tempRe.get(i).get("SummaryDate").toString().substring(8, 10));
//					yArray[i] = tempCal;
//					xArray[i] = tempSumDate;
//				}
				
				ArrayList<Date> weekDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = (Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData)/Double.parseDouble(tempRe.get(i).get("SportTime").toString());
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					weekDates.add(tempD1);
				}
				double[] yReArray = new double[7];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < weekDates.size(); i++)
				{
					int tempD = weekDates.get(i).getDay();
					yReArray[tempD] = yArray[i];
				}
				
				
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yReArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 2)//按月
			{
				String sql = "SELECT Distance,SummaryDate,SportTime FROM XFIT_Day_Summary WHERE UserID=91 AND SummaryDate BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY SummaryDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql,context);
				if (tempRe.size() == 0)
				{
					return result;
				}
				double[] yArray = new double[tempRe.size()];

				int dayNum = getTheDayNumOfMonth(tempS.getYear(),tempS.getMonth());//取日期所在月份的天数
				ArrayList<Date> monthDates = new  ArrayList<Date>();
				
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = (Double.parseDouble(tempRe.get(i).get("Distance").toString())*adjustData)/Double.parseDouble(tempRe.get(i).get("SportTime").toString());
					 //字符串中的日期格式  
			        Date tempD1 = from_type.parse(tempRe.get(i).get("SummaryDate").toString());
					monthDates.add(tempD1);
				}
				double[] yReArray = new double[dayNum];
				for (int i = 0; i < yReArray.length; i++)
				{
					yReArray[i] = 0.0;
				}
				for (int i = 0; i < monthDates.size(); i++)
				{
					int tempD = monthDates.get(i).getDate();
					yReArray[tempD-1] = yArray[i];
				}
				
				//result.put("timeBucket", timeBucket);
				result.put("yArray", yArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 3)
			{
				double[] yArray = new double[12];
				
				for (int i = 0; i < 12; i++)
				{
					Date temp = new Date();
					temp.setYear(tempS.getYear());
					temp.setMonth(i);
					temp.setDate(1);
					temp.setHours(0);
					temp.setMinutes(0);
					temp.setSeconds(0);
					
					yArray[i] = getMonthSum(temp, Integer.parseInt(UserID), context,iShowType)*adjustData;
				}
				//result.put("timeBucket", String.valueOf(tempS.getYear()) + "�?月~12�?);
				result.put("yArray", yArray);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
			}
			else if (iTimeType == 0)//按日
			{
//				double[] yArray = new double[24];
//				Date temp = new Date(selDate.getTime());
//				for (int i = 0; i < 24; i++)
//				{
//					temp.setHours(i);
//					temp.setMinutes(1);
//					temp.setSeconds(1);
//					
//					yArray[i] = getHourSum(temp, UserID, context, iShowType);
//				}
//				
//				result.put("timeBucket", selDate.toString());
//				result.put("yArray", yArray);
//				result.put("startTime", tempS);
//				result.put("endTime", tempE);
				Hashtable resultTemp = new Hashtable();
				double adjustmentData = getAdjustmentData(Integer.parseInt(UserID), context);
				String sql2 = "select AverageSpeed from XFIT_Speed_Detail where UserID="+UserID+" and TrackDate between '"+startTime + "' and '" + endTime + "' order by TrackDate";
				ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
				tempRe = ds.ExecuteReader1(sql2,context);
				double[] yArray = new double[tempRe.size()];
				for (int i = 0; i < tempRe.size(); i++)
				{
					yArray[i] = Double.parseDouble(tempRe.get(i).get("AverageSpeed").toString());
				}
				//double[] yArray = oneDaySummary(startTime,endTime,context,"speed",Integer.parseInt(UserID));
				result.put("yArray", yArray);
				tempS.setHours(0);
				tempS.setMinutes(0);
				tempS.setSeconds(0);
				tempE.setHours(23);
				tempE.setMinutes(59);
				tempE.setSeconds(59);
				result.put("startTime", tempS);
				result.put("endTime", tempE);
				
			}
		}
		
		return result;
	}
	
	public Hashtable getOneReportByLatestTime(Context context)
	{
		Hashtable result = new Hashtable();
		String userid = "";
		String sql1 = "select UserID from XFIT_User_Info order by User_LastTimeD";
		ArrayList<Dictionary> tempRe1 = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe1 = ds.ExecuteReader1(sql1,context);
		if (tempRe1.size() >= 1)
		{
	         userid = tempRe1.get(tempRe1.size()-1).get("UserID").toString();
		}
		else
		{
			userid = "0";
		}
		
		String sql2 = "select * from MonthWeekYearReport where WeekMonthYear=1 and UserId=" + userid + " limit 1";
		ArrayList<Dictionary> tempRe = ds.ExecuteReader1(sql2,context);
		if (tempRe.size() == 0)
		{
			return result;
		}
		double adjustData = getAdjustmentData(Integer.parseInt(tempRe.get(0).get("UserId").toString()), context);//用户调整数据
		String startT = tempRe.get(0).get("StartDate").toString();
		String endT = tempRe.get(0).get("EndDate").toString();
		try {
			result = getOneReport(tempRe.get(0).get("UserId").toString(), Integer.parseInt(tempRe.get(0).get("WeekMonthYear").toString()), startT, endT, Integer.parseInt(tempRe.get(0).get("ShowType").toString()), context, adjustData, ds, 1, 0);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public Hashtable getOneReportById(int id, Context context) throws NumberFormatException, ParseException
	{

		Hashtable result = new Hashtable();
		String sql1 = "select * from MonthWeekYearReport where ID=" + id;
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql1,context);
		double adjustData = getAdjustmentData(Integer.parseInt(tempRe.get(0).get("UserId").toString()), context);//用户调整数据
		String startT = tempRe.get(0).get("StartDate").toString();
		String endT = tempRe.get(0).get("EndDate").toString();
		int isSpeed = 0;//判断是否是跑步详细信息收藏
		if (Integer.parseInt(tempRe.get(0).get("WeekMonthYear").toString()) == 3)
		{
			isSpeed = 1;
		}
		result = getOneReport(tempRe.get(0).get("UserId").toString(), Integer.parseInt(tempRe.get(0).get("WeekMonthYear").toString()), startT, endT, Integer.parseInt(tempRe.get(0).get("ShowType").toString()), context, adjustData, ds, 1, isSpeed);
		result.put("ID", tempRe.get(0).get("ID").toString());
		return result;
	}
	
	/**
	 * @return result key("iTimeType"时间类型,
	 * 					  "iShowType"显示类型,
	 * 					  "timeBucket"时间段,
	 *                    "startTime"开始时间,
	 *                    "endTime"结束时间,
	 *                    "yArray"y轴的值
	 *                    "ID")
	 * @throws ParseException
	 */
	//开机时得到所有报表
	public ArrayList getReports(int userId, Context context) throws ParseException
	{
		double adjustData = getAdjustmentData(userId, context);//用户调整数据
		ArrayList finalResult = new ArrayList();
		String sql = "select ID,StartDate,EndDate,WeekMonthYear,UserId,ShowType from MonthWeekYearReport where UserId=" + String.valueOf(userId)+" order by ID";
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);//取收藏报表table中的所有数�?
		if (tempRe.size() >= 1)
		{
			for (int i = 0; i < tempRe.size(); i++)
			{
				Hashtable result = new Hashtable();
				String startT = tempRe.get(i).get("StartDate").toString();
				String endT = tempRe.get(i).get("EndDate").toString();
				int ID = Integer.parseInt(tempRe.get(i).get("ID").toString());
				result = getOneReport(tempRe.get(i).get("UserId").toString(), Integer.parseInt(tempRe.get(i).get("WeekMonthYear").toString()), startT, endT, Integer.parseInt(tempRe.get(i).get("ShowType").toString()), context, adjustData, ds, 1, 1);
				result.put("ID", ID);
				
				finalResult.add(result);
			}
		}
		return finalResult;
	}
	
	
	@SuppressWarnings("deprecation")
	public Hashtable getTimeBucket(Date selDate, int iTimeType)
	{
		Hashtable result = new Hashtable();
		Date startDate = new Date();
		Date endDate = new Date();
		if (iTimeType == 1)//按周
		{

			int dayNum = getTheDayNumOfMonth(selDate.getYear(),selDate.getMonth());//取日期所在月份的天数


			int condi = 0;
			condi = selDate.getDate()-selDate.getDay();
			if (condi > 0)
			{

				
				startDate.setYear(selDate.getYear());
				startDate.setDate(condi);
				startDate.setMonth(selDate.getMonth());
				startDate.setHours(0);
				startDate.setMinutes(0);
				startDate.setSeconds(0);
			}
			else if (condi <= 0 && selDate.getMonth() != 0)//所选日期不是一月份
			{
				int dateOfMonth = 0;
				dateOfMonth = condi + getTheDayNumOfMonth(selDate.getYear(), selDate.getMonth()-1);//求上一个月的天数
				startDate.setYear(selDate.getYear());
				startDate.setMonth(selDate.getMonth()-1);
				startDate.setDate(dateOfMonth);
				startDate.setHours(0);
				startDate.setMinutes(0);
				startDate.setSeconds(0);
			}
			else if (condi <= 0 && selDate.getMonth() == 0)
			{
				int dateOfMonth = 0;
				dateOfMonth = condi + 31;//12月份都是31天
				startDate.setYear(selDate.getYear()-1);
				startDate.setMonth(11);
				startDate.setDate(dateOfMonth);
				startDate.setHours(0);
				startDate.setMinutes(0);
				startDate.setSeconds(0);
			}

			int endCondi = 0;
			endCondi = selDate.getDate() + (6 - selDate.getDay());//判断此周最后一天是否 getDay()返回值从0（Sunday）开始算
			if (endCondi <= dayNum)//这周周末若是仍然在此月之中
			{
				endDate.setYear(selDate.getYear());
				endDate.setMonth(selDate.getMonth());
				endDate.setDate(endCondi);
				endDate.setHours(23);
				endDate.setMinutes(59);
				endDate.setSeconds(59);
			}
			else if (endCondi > dayNum && selDate.getMonth() < 11)
			{
				endDate.setYear(selDate.getYear());
				endDate.setMonth(selDate.getMonth()+1);
				endDate.setDate(endCondi-dayNum);
				endDate.setHours(23);
				endDate.setMinutes(59);
				endDate.setSeconds(59);
			}
			else if (endCondi > dayNum && selDate.getMonth() == 11)
			{

				endDate.setYear(selDate.getYear()+1);
				endDate.setMonth(0);
				endDate.setDate(endCondi-dayNum);
				endDate.setHours(23);
				endDate.setMinutes(59);
				endDate.setSeconds(59);
				
			}
			Timestamp tsStart = new Timestamp(startDate.getTime());
			Timestamp tsEnd = new Timestamp(endDate.getTime());
			tsStart.setSeconds(0);
			java.sql.Date endD = new java.sql.Date(endDate.getTime());
			java.sql.Date startD = new java.sql.Date(startDate.getTime());
			result.put("TimeBucket", startD.toString() + "到" + endD.toString());
			result.put("StartTime",  tsStart);
			result.put("StartTimeUtil", startDate);
			
			result.put("EndTime",  tsEnd);
			result.put("EndTimeUtil",  endDate);
		
		}
		else if (iTimeType == 2)//按月
		{
			startDate.setYear(selDate.getYear());
			startDate.setMonth(selDate.getMonth());
			startDate.setDate(1);
			
			
			startDate.setHours(0);
			startDate.setMinutes(0);
			startDate.setSeconds(0);
			
			int endOfMonth = getTheDayNumOfMonth(selDate.getYear(),selDate.getMonth());
			endDate.setYear(selDate.getYear());
			endDate.setMonth(selDate.getMonth());
			
			endDate.setDate(endOfMonth);

			endDate.setHours(0);
			endDate.setMinutes(0);
			endDate.setSeconds(0);
			
			Timestamp tsStart = new Timestamp(startDate.getTime());
			Timestamp tsEnd = new Timestamp(endDate.getTime());
			tsStart.setSeconds(0);
			
			java.sql.Date startD = new java.sql.Date(startDate.getTime());
			result.put("StartTime",  tsStart);
			java.sql.Date endD = new java.sql.Date(endDate.getTime());
			result.put("EndTime",  tsEnd);
			result.put("StartTimeUtil", startDate);
			result.put("EndTimeUtil",  endDate);
			result.put("TimeBucket", startD.toString() + "到" + endD.toString());
		}
		else if (iTimeType == 3)
		{
			startDate.setYear(selDate.getYear());
			startDate.setMonth(0);
			startDate.setDate(1);
			
			
			startDate.setHours(0);
			startDate.setMinutes(0);
			startDate.setSeconds(0);
			
			endDate.setYear(selDate.getYear());
			endDate.setMonth(11);
			endDate.setDate(31);
			
			
			endDate.setHours(0);
			endDate.setMinutes(0);
			endDate.setSeconds(0);
			
			Timestamp tsStart = new Timestamp(startDate.getTime());
			Timestamp tsEnd = new Timestamp(endDate.getTime());
			tsStart.setSeconds(0);
			result.put("TimeBucket", tsStart.toString() + "到" + tsEnd.toString());
			java.sql.Date startD = new java.sql.Date(startDate.getTime());
			result.put("StartTime",  tsStart);
			java.sql.Date endD = new java.sql.Date(endDate.getTime());
			result.put("EndTime",  tsEnd);
			result.put("StartTimeUtil", startDate);
			result.put("EndTimeUtil",  endDate);
			result.put("TimeBucket", startD.toString() + "到" + endD.toString());
		}
		else if (iTimeType == 0)
		{			
			startDate.setYear(selDate.getYear());
			startDate.setMonth(selDate.getMonth());
			startDate.setDate(selDate.getDate());
			startDate.setHours(0);
			startDate.setMinutes(0);
			startDate.setSeconds(0);
			
			endDate.setYear(selDate.getYear());
			endDate.setMonth(selDate.getMonth());
			endDate.setDate(selDate.getDate());
			endDate.setHours(23);
			endDate.setMinutes(59);
			endDate.setSeconds(59);
			
			Timestamp tsStart = new Timestamp(startDate.getTime());
			Timestamp tsEnd = new Timestamp(endDate.getTime());
			tsStart.setSeconds(0);
			result.put("TimeBucket", tsStart.toString() + "到" + tsEnd.toString());
			java.sql.Date startD = new java.sql.Date(startDate.getTime());
			result.put("StartTime",  tsStart);
			java.sql.Date endD = new java.sql.Date(endDate.getTime());
			result.put("EndTime",  tsEnd);
			result.put("StartTimeUtil", startDate);
			result.put("EndTimeUtil",  endDate);
			result.put("TimeBucket", startD.toString() + "到" + endD.toString());
		}
		return result;
	}
	
	public int loginLocal(String userName, String passWord, Context context)
	{
		int userid = 0;
		if (userName.equals("admin"))
		{
			userName = "admin@admin";
		}
		String sql = "select UserID from XFIT_User_Info where User_Email='"+userName+"' and Password='"+passWord+"'";
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		if (tempRe.size() >= 1)
		{
			userid = Integer.parseInt(tempRe.get(0).get("UserID").toString());
		}
		return userid;
	}
	
	private String url = "http://xfittest.ordinate.cn/Appsystem/ExtSystem/XFIT/Interface/MobileInterface.asmx";
	private String wsNamespace = "http://Interface.yundongling.com/";
	
	/**
	 * @param userName
	 * @param passWord
	 * @param client_vernumber
	 * @return User的sessionID
	 */
	public String login(String userName, String passWord, String client_vernumber)
	{
		String result = "";
		String soapAction = "http://Interface.yundongling.com/LoginWithUsername";
		String methodName = "LoginWithUsername";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		rpc.addProperty("username", userName);
		rpc.addProperty("password", passWord);
		rpc.addProperty("client_vernumber", client_vernumber);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);

			SoapObject detail =(SoapObject)envelope.getResponse();
			
			String date = detail.getProperty(0).toString();
			
			String temp = date.split(";")[0];
			String sessionID = temp.substring(15);
			
			result = sessionID;
			
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	public boolean updateUserInfo(String email, String password, String newPassword, String birthday, String height, String weight, String gender, String province, String city, String area, String target, Context context)
	{
		boolean result = false;
		if (email.equals("admin"))
		{
			email = "admin@admin";
		}
		if (newPassword.equals(""))
		{
			result = updateUserInfo1(email, password, birthday, height, weight, gender, province, city, area, target);
			updateUserInfoLocal(email, password, context);
		}
		else
		{
			result = changePassword(email, password, newPassword);
			result = updateUserInfo1(email, password, birthday, height, weight, gender, province, city, area, target);
			updateUserInfoLocal(email, newPassword, context);
		}
		return result;
	}
	
	public void updateUserInfoLocal(String email, String password, Context context)
	{
		ContentValues infoFromNet = this.getUserInfoNet(email, password);
		
		String sql = "update XFIT_User_Info set User_Weight='"+infoFromNet.getAsString("User_Weight")+
				"',User_Height="+infoFromNet.getAsString("User_Height")+
				",User_Gender='"+infoFromNet.getAsString("User_Gender")+
				"',User_Birthday='"+infoFromNet.getAsString("User_Birthday")+
				"',User_LastTimeD='"+infoFromNet.getAsString("User_LastTimeD")+
				"',User_Adjustment_Data="+infoFromNet.getAsString("User_Adjustment_Data")+
				",StreetAddress='"+infoFromNet.getAsString("StreetAddress")+
				"',Password='"+infoFromNet.getAsString("Password")+"' where User_Email='"+email+"'";
		DBServices ds = new DBServices();
		ds.executeUpdate(sql, context);
	}
	
	public boolean changePassword(String userName, String oldPassword, String newPassword)
	{
		boolean result = false;
		String soapAction = "http://Interface.yundongling.com/ChangePassword";
		String methodName = "ChangePassword";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		rpc.addProperty("userName", userName);
		rpc.addProperty("oldPassword", oldPassword);
		rpc.addProperty("newPassword", newPassword);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);

			SoapObject detail =(SoapObject) envelope.getResponse();
			
			String date = detail.getProperty(0).toString();
			
			if (!date.contains("您"))
			{
				result = true;
			}
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public boolean updateUserInfo1(String email, String password, String birthday, String height, String weight, String gender, String province, String city, String area, String target)
	{
		boolean result = false;
		String soapAction = "http://Interface.yundongling.com/UpdateUserInfo";
		String methodName = "UpdateUserInfo";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		rpc.addProperty("email", email);
		rpc.addProperty("password", password);
		rpc.addProperty("birthday", birthday);
		rpc.addProperty("height", String.valueOf(height));
		rpc.addProperty("weight", String.valueOf(weight));
		rpc.addProperty("gender", gender);
		rpc.addProperty("province", province);
		rpc.addProperty("city", city);
		rpc.addProperty("area", area);
		rpc.addProperty("target", target);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);

			SoapObject detail =(SoapObject) envelope.getResponse();
			
			String date = detail.getProperty(0).toString();
			
			if (!date.contains("您"))
			{
				result = true;
			}
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public ContentValues getUserInfo(String email, Context context)
	{
		ContentValues result = new ContentValues();
		if (email.equals("admin"))
		{
			email = "admin@admin";
		}
		String sql = "select * from XFIT_User_Info where User_Email='"+email+"'";
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		if (tempRe.size() != 0)
		{
		result.put("User_Weight", tempRe.get(0).get("User_Weight").toString());
		result.put("User_Height", tempRe.get(0).get("User_Height").toString());
		result.put("User_Gender", tempRe.get(0).get("User_Gender").toString());
		result.put("User_Birthday", tempRe.get(0).get("User_Birthday").toString());
		result.put("User_LastTimeD", tempRe.get(0).get("User_LastTimeD").toString());
		result.put("User_LastUploadDate", "");
		result.put("User_HardwareID", "");
		result.put("User_Adjustment_Data", tempRe.get(0).get("User_Adjustment_Data").toString());
		result.put("UserID", tempRe.get(0).get("UserID").toString());
		result.put("User_Email", tempRe.get(0).get("User_Email").toString());
		result.put("StreetAddress", tempRe.get(0).get("StreetAddress").toString());
		}
		else
		{
			result.put("User_Weight", "");
			result.put("User_Height", "");
			result.put("User_Gender", "");
			result.put("User_Birthday", "");
			result.put("User_LastTimeD", "");
			result.put("User_LastUploadDate", "");
			result.put("User_HardwareID", "");
			result.put("User_Adjustment_Data", "");
			result.put("UserID", "");
			result.put("User_Email", "");
			result.put("StreetAddress", "");
		}
		return result;
	}
	
	public ContentValues getUserInfoNet(String email, String password)
	{
		ContentValues result = new ContentValues();
		String soapAction = "http://Interface.yundongling.com/GetUserInfo";
		String methodName = "GetUserInfo";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		rpc.addProperty("email", email);
		rpc.addProperty("password", password);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);

			SoapObject detail =(SoapObject) envelope.getResponse();
			
			String date = detail.getProperty(0).toString();
			
			if (date.contains("错误"))
			{
				result=null;
				return result;
			}
			
			String temp1 = date.substring(40);
			

			
			String[] temp2 = temp1.split(";");
			String[] info = new String[temp2.length-3];
			for (int i = 0; i < temp2.length-3; i++)
			{
				String[] temp3 = temp2[i].split("=");
				info[i] = temp3[1];
			}
			
			String UserID = "";
			String AdjustmentData = "";
			String Gender = "";
			String Email = "";
			String Age = "";
			String Height = "";
			String Weight = "";
			String Sex = "";
			String StreetAddress = "";
			String Target = "";
			String Birthday = "";
			
			if (!info[0].equals("anyType{}"))
			{
				UserID = info[0];
			}
			
			if (!info[1].equals("anyType{}"))
			{
				Email = info[1];
			}
			
			if (!info[2].equals("anyType{}"))
			{
				Birthday = info[2];
			}
			
			if (!info[3].equals("anyType{}"))
			{
				Age = info[3];
			}
			
			if (!info[4].equals("anyType{}"))
			{
				Height = info[4];
			}
			
			if (!info[5].equals("anyType{}"))
			{
				Weight = info[5];
			}
			
			if (!info[6].equals("anyType{}"))
			{
				Sex = info[6];
			}
			
			if (!info[7].equals("anyType{}"))
			{
				StreetAddress = info[7];
			}
			
			if (!info[8].equals("anyType{}"))
			{
				Target = info[8];
			}
			
			if (!info[9].equals("anyType{}"))
			{
				AdjustmentData = info[9];
			}
			
			Calendar c = Calendar.getInstance();
			java.sql.Timestamp st = new java.sql.Timestamp(c.getTimeInMillis());
			
			result.put("User_Weight", Weight);
			result.put("User_Height", Height);
			result.put("User_Gender", Sex.trim());
			result.put("User_Birthday", Birthday);
			result.put("User_LastTimeD", st.toString());
			result.put("User_LastUploadDate", "");
			result.put("User_HardwareID", "");
			result.put("User_Adjustment_Data", AdjustmentData);
			result.put("UserID", UserID);
			result.put("User_Email", Email);
			result.put("StreetAddress", StreetAddress);
			result.put("Password", password);
			
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * @param email
	 * @param password
	 * @param birthday
	 * @param height
	 * @param weight
	 * @param gender
	 * @param latestLogin
	 * @param uploadDate
	 * @param User_HardwareID
	 * @param User_Adjustment_Data
	 * @param UserID
	 * @param province
	 * @param city
	 * @param area
	 * @return 被打包成ContentValues的userinfo
	 */
	public ContentValues packagingUserInfo(String email, String password, String birthday, double height, double weight, String gender, Date latestLogin, Date uploadDate, String User_HardwareID, double User_Adjustment_Data, int UserID, String province, String city, String area)
	{
		ContentValues cValue = new ContentValues();
		cValue.put("User_Weight", String.valueOf(weight));
		cValue.put("User_Height", String.valueOf(height));
		cValue.put("User_Gender", gender);
		cValue.put("User_Birthday", birthday);
		java.sql.Timestamp TrackD=new java.sql.Timestamp(latestLogin.getTime());
		cValue.put("User_LastTimeD", TrackD.toString());
		java.sql.Timestamp LatestUploadDate=new java.sql.Timestamp(uploadDate.getTime());
		cValue.put("User_LastUploadDate", LatestUploadDate.toString());
		cValue.put("User_HardwareID", User_HardwareID);
		cValue.put("User_Adjustment_Data", String.valueOf(User_Adjustment_Data));
		cValue.put("UserID", String.valueOf(UserID));
		cValue.put("User_Email", email);
		cValue.put("StreetAddress", province + " " + city + " " + area);
		return cValue;
	}
	
	public long insertUserLocal(Context context, String email, String password, String birthday, double height, double weight, String gender, Date latestLogin, Date uploadDate, String User_HardwareID, double User_Adjustment_Data, int UserID, String province, String city, String area)
	{
		ContentValues info = packagingUserInfo(email, password, birthday, height, weight, gender, latestLogin, uploadDate, User_HardwareID, User_Adjustment_Data, UserID, province, city, area);
		String tName = "XFIT_User_Info";
		DBServices dbs = new DBServices();
		long tempRe = dbs.ExecuteInsertSingle(info, context, tName);
		return tempRe;
	}
	
	public long insertUserLocal1(Context context, ContentValues info)
	{
		String tName = "XFIT_User_Info";
		DBServices dbs = new DBServices();
		long tempRe = dbs.ExecuteInsertSingle(info, context, tName);
		return tempRe;
	}
	
	
	
	/**
	 * @param context
	 * @param email
	 * @param password
	 * @param birthday
	 * @param height
	 * @param weight
	 * @param gender
	 * @param province
	 * @param city
	 * @param area
	 * @param target
	 * @param latestLoginTime
	 * @return Hashtable<String,Object> "userID" "sessionID"
	 */
	public Hashtable<String,Object> registerAndLogin(Context context, String email, String password, String birthday, double height, double weight, String gender, String province, String city, String area, String target)
	{
		Hashtable<String,Object> result = new Hashtable<String,Object>();
		String tempree = register(email, password, birthday, height, weight, gender, province, city, area, target);
		if (tempree != "")
		{
			int userID = Integer.parseInt(tempree);
			if (userID != -1)
			{
				result.put("userID", userID);
				String sessionID = login(email, password, "a");
				if (sessionID.toLowerCase().contains("error"))
				{
					result.put("sessionID", "error");
					return result;
				}
				result.put("sessionID", sessionID);
				long m=System.currentTimeMillis();
				Date latestLogin = new Date(m);
				Date uploadDate = new Date(100,0,1);
				ContentValues cv = getUserInfoNet(email, password);
				long temppp = insertUserLocal1(context, cv);
			}
			else
			{
				result.put("userID", userID);
				result.put("sessionID", "error");
			}
		}
		
		return result;
	}
	
	/**
	 * @param userName
	 * @param passWord
	 * @param client_vernumber
	 * @param context
	 * @return Hashtable<String,Object> "userID" "sessionID"
	 * 
	 * 已有用户登陆
	 */
	public Hashtable<String,Object> myLogin(String userName, String passWord, String client_vernumber, Context context)
	{
		Hashtable<String,Object> result = new Hashtable<String,Object>();
		String sessionID = login(userName, passWord, "a");
		ContentValues cv = getUserInfoNet(userName, passWord);
		if (sessionID.toLowerCase().contains("error"))
		{
			result.put("sessionID", "error");
		}
		else
		{
			result.put("sessionID", sessionID);
		}

		if((null == cv)||(cv.size() == 0))
		{
			result.put("userID", "error");
			return result;
		}
		
		result.put("userID", cv.getAsString("UserID"));
		//判断本地数据库里是否有此用户，若无，插入信息
		String sql = "select count(*) as Count from XFIT_User_Info where UserID=" + cv.getAsString("UserID");
		ArrayList<Dictionary> tempRe = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe = ds.ExecuteReader1(sql,context);
		if (tempRe.get(0).get("Count").toString().equals("0"))
		{
			String tName = "XFIT_User_Info";
			long tempRe1 = ds.ExecuteInsertSingle(cv, context, tName);
		}
		else
		{
			String lastLoginTime = cv.getAsString("User_LastTimeD");
			String updateSql = "update XFIT_User_Info set User_LastTimeD='"+lastLoginTime+"'";
	        ds.executeUpdate(updateSql, context);
		}
		return result;
	}
	
	
	
	public int uploadDataToServer(String sessionID, String data, String client_vernumber)
	{
		int result = -1;
		String soapAction = "http://Interface.yundongling.com/UploadData";
		String methodName = "UploadData";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		rpc.addProperty("sessionId", sessionID);
		rpc.addProperty("data", data);
		rpc.addProperty("client_vernumber", client_vernumber);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);
			if (envelope.getResponse() != null)
			{
				String res = envelope.getResponse().toString();
				result = Integer.parseInt(res);
			}
			
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public void clearAllStepsData(Context context)
	{
		String sql = "delete from Steps_Detail";
		DBServices ds = new DBServices();
		ds.executeDelete(sql, context);
	}
	
	public long deleteAndDownload20Elment(Context context, String sessionId, int userID,int runningID, String client_vernumber)
	{
		long result = 0;
		String sql = "select StartTime,EndTime from XFIT_Per_Running where UserID="+String.valueOf(userID)+" and RunningID=" + String.valueOf(runningID);
		DBServices ds = new DBServices();
		ArrayList<Dictionary> temp = new ArrayList<Dictionary>();
		temp = ds.ExecuteReader1(sql, context);
		String startTime = temp.get(0).get("StartTime").toString();
		String endTime = temp.get(0).get("EndTime").toString();
		
		DateFormat from_type1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			Date startDate = from_type1.parse(startTime);
			Date endDate = from_type1.parse(endTime);
			ArrayList<ContentValues> tempResult = this.downloadData(sessionId, startDate, endDate, client_vernumber, 2);
			if (tempResult.size() == 0)
			{
				return result;
			}
			else
			{
				String sql1 = "delete from XFIT_Speed_Detail where TrackDate between '" + startTime + "' and '" + endTime + "'";
				ds = new DBServices();
				ds.executeDelete(sql1, context);

				String tName = "XFIT_Speed_Detail";
				DBServices dbs = new DBServices();
				result = dbs.ExecuteInsertMultiple(tempResult, context, tName);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	public long deleteAndDownloadData(String userId, String sessionId, Date selDate, String client_vernumber, int iShowType, int iTimeType, Context context) throws ParseException
	{
		long result = 0;
		Hashtable temp = getTimeBucket(selDate, iTimeType);
		
		DBServices ds = new DBServices();
		String startTime = temp.get("StartTime").toString();
		String endTime = temp.get("EndTime").toString();
		DateFormat from_type1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date startDate = from_type1.parse(startTime);
		Date endDate = from_type1.parse(endTime);
		if (iTimeType == 0 && iShowType == 0)
		{
			ArrayList<ContentValues> tempResult = this.downloadData(sessionId, startDate, endDate, client_vernumber, 2);
			if (tempResult.size() == 0)
			{
				if(strErrorMessage == "您查询的数据不存在")
				{
					result = 2;
				}
				return result;
			}
			else
			{
				long num = this.deleteAndDownloadDaySumOne(userId, startTime, context, sessionId, client_vernumber, ds);
				String sql = "delete from XFIT_Speed_Detail where TrackDate between '" + startTime + "' and '" + endTime + "'";
				ds = new DBServices();
				ds.executeDelete(sql, context);

				String tName = "XFIT_Speed_Detail";
				DBServices dbs = new DBServices();
				result = dbs.ExecuteInsertMultiple(tempResult, context, tName);
			}
		}
		else if ((iTimeType == 0 && iShowType == 1) || (iTimeType == 0 && iShowType == 3))
		{
			ArrayList<ContentValues> tempResult = this.downloadData(sessionId, startDate, endDate, client_vernumber, 2);
			if (tempResult.size() == 0)
			{
				return result;
			}
			else
			{
				long num = this.deleteAndDownloadDaySumOne(userId, startTime, context, sessionId, client_vernumber, ds);
				String sql = "delete from XFIT_Speed_Detail where TrackDate between '" + startTime + "' and '" + endTime + "'";
				ds = new DBServices();
				ds.executeDelete(sql, context);

				String tName = "XFIT_Speed_Detail";
				DBServices dbs = new DBServices();
				result = dbs.ExecuteInsertMultiple(tempResult, context, tName);
			}
		}
		else if (iTimeType == 0 && iShowType == 2)
		{
			ArrayList<ContentValues> tempResult = this.downloadData(sessionId, startDate, endDate, client_vernumber, 3);
			if (tempResult.size() == 0)
			{
				return result;
			}
			else
			{
				long num = this.deleteAndDownloadDaySumOne(userId, startTime, context, sessionId, client_vernumber, ds);
				String sql = "delete from XFIT_Tracking_Detail where Track_Date between '" + startTime + "' and '" + endTime + "'";
				ds = new DBServices();
				ds.executeDelete(sql, context);

				String tName = "XFIT_Tracking_Detail";
				DBServices dbs = new DBServices();
				result = dbs.ExecuteInsertMultiple(tempResult, context, tName);
			}
		}
		else
		{
			ArrayList<ContentValues> tempResult = this.downloadData(sessionId, startDate, endDate, client_vernumber, 0);
			if (tempResult.size() == 0)
			{
				return result;
			}
			else
			{
				String sql = "delete from XFIT_Day_Summary where SummaryDate between '" + startTime + "' and '" + endTime + "'";
				ds = new DBServices();
				ds.executeDelete(sql, context);

				String tName = "XFIT_Day_Summary";
				DBServices dbs = new DBServices();
				result = dbs.ExecuteInsertMultiple(tempResult, context, tName);
			}
		}
		
		return result;
	}
	
	
	public Hashtable<String,Timestamp> getLatestDateLocal(int UserID, Context context)
	{
		Hashtable<String,Timestamp> result = new Hashtable<String,Timestamp>();
		String sql1 = "select max(SummaryDate) as latestDate from XFIT_Day_Summary where UserID=" + UserID;
		String sql2 = "select max(StartTime) as latestDate from XFIT_Per_Running where UserID=" + UserID;
		String sql3 = "select max(TrackDate) as latestDate from XFIT_Speed_Detail where UserID=" + UserID;
		String sql4 = "select max(Track_Date) as latestDate from XFIT_Tracking_Detail where UserID=" + UserID;
		ArrayList<Dictionary> tempRe1 = new ArrayList<Dictionary>();
		DBServices ds = new DBServices();
		tempRe1 = ds.ExecuteReader1(sql1,context);
		ArrayList<Dictionary> tempRe2 = new ArrayList<Dictionary>();

		tempRe2 = ds.ExecuteReader1(sql2,context);
		ArrayList<Dictionary> tempRe3 = new ArrayList<Dictionary>();

		tempRe3 = ds.ExecuteReader1(sql3,context);
		ArrayList<Dictionary> tempRe4 = new ArrayList<Dictionary>();

		tempRe4 = ds.ExecuteReader1(sql4,context);
		
		DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1;
		try {
			d1 = from_type.parse(tempRe1.get(0).get("latestDate").toString());
			Date d2 = from_type.parse(tempRe2.get(0).get("latestDate").toString());
			Date d3 = from_type.parse(tempRe3.get(0).get("latestDate").toString());
			Date d4 = from_type.parse(tempRe4.get(0).get("latestDate").toString());
			Timestamp stamp1 = new Timestamp(d1.getTime());
			Timestamp stamp2 = new Timestamp(d2.getTime());
			Timestamp stamp3 = new Timestamp(d3.getTime());
			Timestamp stamp4 = new Timestamp(d4.getTime());
			result.put("trackTime", stamp1);
			result.put("speedtrackTime", stamp2);
			result.put("runningTime", stamp3);
			result.put("dSummaryTime", stamp4);
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		return result;
	}
	
	public Hashtable<String,Timestamp> getLatestDateFromServer()
	{
		Hashtable<String,Timestamp> result = new Hashtable<String,Timestamp>();
		String soapAction = "http://Interface.yundongling.com/GetNewDate";
		String methodName = "GetNewDate";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);
			//String resul = envelope.getResponse().toString();
			SoapObject detail  =(SoapObject) envelope.getResponse();
				SoapObject resource = (SoapObject) ((SoapObject) detail.getProperty(0)).getProperty("XFIT_Tracking_Detail");
				SoapObject resource1 = (SoapObject) ((SoapObject) detail.getProperty(0)).getProperty("XFIT_Speed_Detail");
				SoapObject resource2 = (SoapObject) ((SoapObject) detail.getProperty(0)).getProperty("XFIT_Per_Running");
				SoapObject resource3 = (SoapObject) ((SoapObject) detail.getProperty(0)).getProperty("XFIT_Day_Summary");
				String trackDate = resource.getAttributeAsString("DateTime");
				String speedDate = resource1.getAttributeAsString("DateTime");
				String runningDate = resource2.getAttributeAsString("DateTime");
				String dSummaryDate = resource3.getAttributeAsString("DateTime");
				
				String temptrack = getTrueTime(trackDate);
				String tempspeed = getTrueTime(speedDate);
				String temprunning = getTrueTime(runningDate);
				String tempdSummary = getTrueTime(dSummaryDate);
				
				DateFormat from_type = new SimpleDateFormat("yyyy MM dd HH mm ss");
				
				 try {
					Date trackD = from_type.parse(temptrack);
					Date speedD = from_type.parse(tempspeed);
					Date runningD = from_type.parse(temprunning);
					Date dSummaryD = from_type.parse(tempdSummary);
					Timestamp trackStamp = new Timestamp(trackD.getTime());
					Timestamp speedStamp = new Timestamp(speedD.getTime());
					Timestamp runningStamp = new Timestamp(runningD.getTime());
					Timestamp dSummaryStamp = new Timestamp(dSummaryD.getTime());
					result.put("trackTime", trackStamp);
					result.put("speedtrackTime", speedStamp);
					result.put("runningTime", runningStamp);
					result.put("dSummaryTime", dSummaryStamp);
					
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public String getTrueTime(String originTime)
	{
		String result = "";
		StringTokenizer strT1 = new StringTokenizer(originTime," -:");
		int num1 = 0;
		while(strT1.hasMoreTokens())
		{
			String str = strT1.nextToken();
			if (num1 == 0 && str.length() == 4)
			{
				num1++;
				result += str + " ";
				continue;
			}
			else
			{
				if (str.length() == 1) {
					str = "0" + str;
			        }
				result += str + " ";
				num1++;
			}
		}
		return result;
	}
	
	/**
	 * @param email
	 * @param password
	 * @param birthday
	 * @param height
	 * @param weight
	 * @param gender
	 * @param province
	 * @param city
	 * @param area
	 * @param target
	 * @return UserID
	 */
	public String register(String email, String password, String birthday, double height, double weight, String gender, String province, String city, String area, String target )
	{
		String result = "";
		String soapAction = "http://Interface.yundongling.com/UserRegistration";
		String methodName = "UserRegistration";
		SoapObject rpc = new SoapObject(wsNamespace, methodName);
		rpc.addProperty("email", email);
		rpc.addProperty("password", password);
		rpc.addProperty("birthday", birthday);
		rpc.addProperty("height", String.valueOf(height));
		rpc.addProperty("weight", String.valueOf(weight));
		rpc.addProperty("gender", gender);
		rpc.addProperty("province", province);
		rpc.addProperty("city", city);
		rpc.addProperty("area", area);
		rpc.addProperty("target", target);
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);

			SoapObject detail =(SoapObject) envelope.getResponse();
			
			String date = detail.getProperty(0).toString();
			
			String regEx="[^0-9]";
			
			Pattern p = Pattern.compile(regEx);
			
			Matcher m = p.matcher(date);
			
			result = m.replaceAll("").trim();
//			if (!date.matches(regEx))
//			{
//				
//				String temp = date.split("：")[1];
//
//				String temp1 = temp.split(";")[0];
//
//				result = Integer.valueOf(temp1);
//			}
			
			
			
			
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * @param data
	 * @param datatype 数据类型：0为XFIT_Day_Summary数据；1为XFIT_Per_Running数据；2为XFIT_Speed_Detail数据；3为XFIT_Tracking_Detail数据
	 * @return
	 * @throws ParseException 
	 */
	public ArrayList<ContentValues> wrapDownloadedData(String data, int datatype) throws ParseException
	{
		ArrayList<ContentValues> result = new ArrayList<ContentValues>();
		String temp1 = data.split("=")[2];
		
		String temp2 = temp1.split(";")[0];
		
		String[] tempRe1;
		tempRe1 = temp2.split("\n");
		for (int i = 0; i < tempRe1.length; i++)
		{
			String[] temp3 = tempRe1[i].split(",",-1);
			if (datatype == 0 && temp3.length == 6)
			{
				ContentValues cv = packagingDaySumDataString(temp3[0], temp3[1], temp3[2], temp3[3], temp3[4], temp3[5]);
				result.add(cv);
			}
			else if ((datatype == 1 || datatype == 4) && temp3.length == 8)
			{
				ContentValues cv = packagingPerRunningString(temp3[0],temp3[1], temp3[2], temp3[3], temp3[4], temp3[5], temp3[6], temp3[7]);
				result.add(cv);
			}
			else if (datatype == 2 && temp3.length == 6)
			{
				ContentValues cv = packagingSpeedDataString(temp3[0],temp3[1], temp3[2], temp3[3], temp3[4], temp3[5]);
				result.add(cv);
			}
			else if (datatype == 3 && temp3.length == 10)
			{
				ContentValues cv = packagingTrackingDataString(temp3[1],temp3[2], temp3[3], temp3[4], temp3[5], temp3[6], temp3[7], temp3[8], temp3[9]);
				result.add(cv);
			}
		}
		return result;
	}
	
	/**
	 * @param sessionId
	 * @param startDate
	 * @param endDate
	 * @param client_vernumber
	 * @param datatype 
	 * 数据类型：0为XFIT_Day_Summary数据；1为XFIT_Per_Running数据；2为XFIT_Speed_Detail数据；3为XFIT_Tracking_Detail数据
	 * @return
	 * @throws ParseException 
	 */
	public ArrayList<ContentValues> downloadData(String sessionId, Date startDate, Date endDate, String client_vernumber, int datatype) throws ParseException
	{
		ArrayList<ContentValues> result = new ArrayList<ContentValues>();
		String soapAction = "";
		String methodName = "";
		String tName = "";
		SoapObject rpc;
		if (datatype == 0)
		{
			methodName = "GetDaySummaryData";
			
			soapAction = "http://Interface.yundongling.com/GetDaySummaryData";
		}
		else if (datatype == 1)
		{
			methodName = "GetRunData";
			
			soapAction = "http://Interface.yundongling.com/GetRunData";

		}
		else if (datatype == 2)
		{
			methodName = "GetSpeedDetail";
			
			soapAction = "http://Interface.yundongling.com/GetSpeedDetail";
		}
		else if (datatype == 3)
		{
			methodName = "GetTrackingDetail";
			
			soapAction = "http://Interface.yundongling.com/GetTrackingDetail";
		}
		else if (datatype == 4)
		{
			methodName = "GetRunDataEx";
			soapAction = "http://Interface.yundongling.com/GetRunDataEx";

		}
		
		rpc = new SoapObject(wsNamespace, methodName);
		
		if (datatype == 4)
		{
		
			rpc.addProperty("sessionId", sessionId);
			java.sql.Timestamp startD=new java.sql.Timestamp(startDate.getTime());
			rpc.addProperty("startDate", startD.toString());
			java.sql.Timestamp endD=new java.sql.Timestamp(endDate.getTime());
			rpc.addProperty("endDate", endD.toString());
			rpc.addProperty("client_vernumber", client_vernumber);
			rpc.addProperty("recordNum", String.valueOf(20));
		}
		else
		{

		
		rpc.addProperty("sessionId", sessionId);
		java.sql.Timestamp startD=new java.sql.Timestamp(startDate.getTime());
		rpc.addProperty("startDate", startD.toString());
		java.sql.Timestamp endD=new java.sql.Timestamp(endDate.getTime());
		rpc.addProperty("endDate", endD.toString());
		rpc.addProperty("client_vernumber", client_vernumber);
		}
		
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);
			
			ht.debug = true;

			ht.call(soapAction, envelope);

			SoapObject detail =(SoapObject) envelope.getResponse();
			
			String data = detail.getProperty(0).toString();
			
			if (data.contains("您查询的数据不存在"))
			{
				strErrorMessage = "您查询的数据不存在";
				return result;
			}
			else if(data.contains("您"))
			{
				return result;
			}
			else
			{
				result = wrapDownloadedData(data, datatype);
			}

			
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
//	public long whetherPerRunningStrideDay(int userID, Context context,int runningID)
//	{
//		long result = 0;
//		String sql1 = "select StartTime,EndTime from XFIT_Per_Running where UserID="+String.valueOf(userID)+" and RunningID=" + String.valueOf(runningID);
//		DBServices ds = new DBServices();
//		ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
//		RunningDay = ds.ExecuteReader1(sql1,context);
//		DateFormat from_type1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//			Date tempS = from_type1.parse(RunningDay.get(0).get("StartTime").toString());
//			Date tempE = from_type1.parse(RunningDay.get(0).get("EndTime").toString());
//			if (tempS.getDate() != tempE.getDate())
//			{
//				Date dStartTime = new Date();
//			}
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//        
//		
//		return result;
//	}
	
	public long deleteAndDownload20PerRunning(String sessionId, Date selTime, Context context, String UserID, String client_vernumber)
	{
		long result = 0;
		DBServices ds = new DBServices();
		Date selDate = new Date(selTime.getYear(), selTime.getMonth(), selTime.getDate());
		Date startD = new Date(selDate.getYear()-1, selDate.getMonth(), selDate.getDate());
		startD.setHours(0);
		startD.setMinutes(0);
		startD.setSeconds(0);
		Timestamp startTime = new Timestamp(startD.getTime());
		Date endD = new Date(selDate.getYear(), selDate.getMonth(), selDate.getDate());
		endD.setHours(23);
		endD.setMinutes(59);
		endD.setSeconds(59);
		Timestamp endTime = new Timestamp(endD.getTime());
		
		String sql = "delete from XFIT_Per_Running where StartTime between '" + startTime + "' and '" + endTime + "'";
		ds = new DBServices();
		ds.executeDelete(sql, context);
		try {
			result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 4, context);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public long deleteAndDownload20PerRunningDay(String sessionId, Date selTime, Context context, String UserID, String client_vernumber)
	{
		long result = 0;
		DBServices ds = new DBServices();
		Date selDate = new Date(selTime.getYear(), selTime.getMonth(), selTime.getDate());
		int index = 0;
		while (result < 20)
		{
			index++;
			
			Date startD = new Date(selDate.getYear(), selDate.getMonth(), selDate.getDate());
			startD.setHours(0);
			startD.setMinutes(0);
			startD.setSeconds(0);
			Timestamp startTime = new Timestamp(startD.getTime());
			Date endD = new Date(selDate.getYear(), selDate.getMonth(), selDate.getDate());
			endD.setHours(23);
			endD.setMinutes(59);
			endD.setSeconds(59);
			Timestamp endTime = new Timestamp(endD.getTime());
			
			String sql = "delete from XFIT_Per_Running where StartTime between '" + startTime + "' and '" + endTime + "'";
			ds = new DBServices();
			ds.executeDelete(sql, context);
			
			try {
				long tempResult = downloadDataToDB(sessionId, startD, endD, client_vernumber, 1, context);
				result += tempResult;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Calendar ca = Calendar.getInstance();
			ca.setTime(selDate);
			ca.add(Calendar.DAY_OF_YEAR, -1);
			selDate = ca.getTime();
			
			if (selTime.getMonth() - selDate.getMonth() > 2)//判断何时跳出循环
			{
				break;
			}
			else if (selTime.getMonth() - selDate.getMonth() < 0 && Math.abs(selTime.getMonth() - selDate.getMonth()) <= 10)
			{
				break;
			}
		}
		return result;
	}
	
	
	
	
	
	public long download20PerRunning(String sessionId, Date selTime, Context context, String UserID, String client_vernumber)
	{
		
		long result = 0;
		DBServices ds = new DBServices();
		Date selDate = new Date(selTime.getYear(), selTime.getMonth(), selTime.getDate());
		int index = 0;
		while (result < 20)
		{
			index++;
			String day = String.valueOf(selDate.getYear() + 1900) + String.valueOf(selDate.getMonth() + 1) + String.valueOf(selDate.getDate());
			String sql = "select count(RunningDay) as Num from pRunningDayTable where RunningDay='" + day + "' and UserID=" + UserID;
			ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
			RunningDay = ds.ExecuteReader1(sql,context);
			String count = RunningDay.get(0).get("Num").toString();
			if (count.equals("0"))
			{
				Date startD = new Date(selDate.getYear(), selDate.getMonth(), selDate.getDate());
				startD.setHours(0);
				startD.setMinutes(0);
				startD.setSeconds(0);
				Date endD = new Date(selDate.getYear(), selDate.getMonth(), selDate.getDate());
				endD.setHours(23);
				endD.setMinutes(59);
				endD.setSeconds(59);
				try {
					long tempp = downloadDataToDB(sessionId, startD, endD, client_vernumber, 1, context);
					result += tempp;
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ContentValues cVals = new ContentValues();
				cVals.put("UserID", UserID);
				cVals.put("RunningDay", day);
				String tName = "pRunningDayTable";
				long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
			}
			else
			{
			
				java.sql.Date selDateTime = new java.sql.Date(selDate.getTime());

				String sqlCheckNum = "select count(*) as Num from XFIT_Per_Running where UserID="+UserID+" and StartTime between '" + selDateTime.toString() + " 00:00:00" + "' and '" + selDateTime.toString() +  " 23:59:59" + "'";
				ArrayList<Dictionary> perNum = new ArrayList<Dictionary>();
				perNum = ds.ExecuteReader1(sql,context);
				int num = Integer.parseInt(RunningDay.get(0).get("Num").toString());
				result += num;
			}
//			int year = selDate.getYear();
//			int month = selDate.getMonth();
//			int date = selDate.getDate();
//			
//			date--;
//			if (date <= 0)
//			{
//				month--;
//				tempMonth = selDate.getMonth() - 1;
//			}
//			
//			if (month < 0)
//			{
//				year--;
//			}
//			
//			if ((year + 1900) < 2000)
//			{
//				break;
//			}
			
			Calendar ca = Calendar.getInstance();
			ca.setTime(selDate);
			ca.add(Calendar.DAY_OF_MONTH, -1);
			selDate = ca.getTime();
			if ((selDate.getYear() + 1900) <= 2000)
			{
				break;
			}
		}
		return result;
	}
	
	
	
	public long downloadPartDataToDB(String userId, String sessionId, Date selDate, String client_vernumber, int iShowType, int iTimeType, Context context) throws ParseException
	{
		long result = 0;
		Hashtable temp = getTimeBucket(selDate, iTimeType);
		
		DBServices ds = new DBServices();
		String startTime = temp.get("StartTime").toString();
		String endTime = temp.get("EndTime").toString();
		DateFormat from_type1 = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = from_type1.parse(startTime);
		Date endDate = from_type1.parse(endTime);
		if (iTimeType == 0 && iShowType == 0)
		{
			String date = String.valueOf(startDate.getYear() + 1900) + String.valueOf(startDate.getMonth() + 1) + String.valueOf(startDate.getDate());
			String tempsql = "select count(RunningDay) as Num from pRunningDayTable where RunningDay='" + date + "' and UserID=" + userId;
			ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
			RunningDay = ds.ExecuteReader1(tempsql,context);
			String count = RunningDay.get(0).get("Num").toString();
			if (count.equals("0"))
			{
				Date startD = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate());
				startD.setHours(0);
				startD.setMinutes(0);
				startD.setSeconds(0);
				Date endD = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate());
				endD.setHours(23);
				endD.setMinutes(59);
				endD.setSeconds(59);
				result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 1, context);
				ContentValues cVals = new ContentValues();
				cVals.put("UserID", userId);
				cVals.put("RunningDay", date);
				String tName = "pRunningDayTable";
				long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
			}
				
		}
		else if ((iTimeType == 0 && iShowType == 1) || (iTimeType == 0 && iShowType == 3))
		{
			String date = String.valueOf(startDate.getYear() + 1900) + String.valueOf(startDate.getMonth() + 1) + String.valueOf(startDate.getDate());
			String tempsql = "select count(SpeedDay) as Num from speedDayTable where SpeedDay='" + date + "' and UserID=" + userId;
			ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
			RunningDay = ds.ExecuteReader1(tempsql,context);
			String count = RunningDay.get(0).get("Num").toString();
			if (count.equals("0"))
			{
				Date startD = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate());
				startD.setHours(0);
				startD.setMinutes(0);
				startD.setSeconds(0);
				Date endD = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate());
				endD.setHours(23);
				endD.setMinutes(59);
				endD.setSeconds(59);
				result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 1, context);
				ContentValues cVals = new ContentValues();
				cVals.put("UserID", userId);
				cVals.put("SpeedDay", date);
				String tName = "speedDayTable";
				long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
			}
		}
		else if (iTimeType == 0 && iShowType == 2)
		{
			String date = String.valueOf(startDate.getYear() + 1900) + String.valueOf(startDate.getMonth() + 1) + String.valueOf(startDate.getDate());
			String tempsql = "select count(trackingDay) as Num from trackingDayTable where trackingDay='" + date + "' and UserID=" + userId;
			ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
			RunningDay = ds.ExecuteReader1(tempsql,context);
			String count = RunningDay.get(0).get("Num").toString();
			if (count.equals("0"))
			{
				Date startD = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate());
				startD.setHours(0);
				startD.setMinutes(0);
				startD.setSeconds(0);
				Date endD = new Date(startDate.getYear(), startDate.getMonth(), startDate.getDate());
				endD.setHours(23);
				endD.setMinutes(59);
				endD.setSeconds(59);
				result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 1, context);
				ContentValues cVals = new ContentValues();
				cVals.put("UserID", userId);
				cVals.put("trackingDay", date);
				String tName = "trackingDayTable";
				long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
			}
		}
		else
		{
			String date = String.valueOf(startDate.getYear() + 1900);
			String dateE = String.valueOf(endDate.getYear() + 1900);
			if (iTimeType == 1)
			{
				if (startDate.getYear() == endDate.getYear())
				{
					String tempsql = "select count(Syear) as Num from yearTable where Syear='" + date + "' and UserID=" + userId;
					ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
					RunningDay = ds.ExecuteReader1(tempsql,context);
					String count = RunningDay.get(0).get("Num").toString();
					if (count.equals("0"))
					{
						Date startD = new Date(startDate.getYear(), 0, 1);
						startD.setHours(0);
						startD.setMinutes(0);
						startD.setSeconds(0);
						Date endD = new Date(startDate.getYear(), 11, 31);
						endD.setHours(23);
						endD.setMinutes(59);
						endD.setSeconds(59);
						result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 0, context);
						ContentValues cVals = new ContentValues();
						cVals.put("UserID", userId);
						cVals.put("Syear", date);
						String tName = "yearTable";
						long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
					}

				}
				else if (startDate.getYear() != endDate.getYear())
				{
					String tempsql = "select count(Syear) as Num from yearTable where Syear='" + date + "' and UserID=" + userId;
					String tempsqlE = "select count(Syear) as Num from yearTable where Syear='" + dateE + "' and UserID=" + userId;
					ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
					ArrayList<Dictionary> RunningDayE = new ArrayList<Dictionary>();
					RunningDay = ds.ExecuteReader1(tempsql,context);
					RunningDayE = ds.ExecuteReader1(tempsqlE,context);
					String count = RunningDay.get(0).get("Num").toString();
					String countE = RunningDayE.get(0).get("Num").toString();
					if (count.equals("0"))
					{
						Date startD = new Date(startDate.getYear(), 0, 1);
						startD.setHours(0);
						startD.setMinutes(0);
						startD.setSeconds(0);
						Date endD = new Date(startDate.getYear(), 11, 31);
						endD.setHours(23);
						endD.setMinutes(59);
						endD.setSeconds(59);
						result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 0, context);
						ContentValues cVals = new ContentValues();
						cVals.put("UserID", userId);
						cVals.put("Syear", date);
						String tName = "yearTable";
						long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
					}
					
					if (countE.equals("0"))
					{
						Date startD = new Date(endDate.getYear(), 0, 1);
						startD.setHours(0);
						startD.setMinutes(0);
						startD.setSeconds(0);
						Date endD = new Date(endDate.getYear(), 11, 31);
						endD.setHours(23);
						endD.setMinutes(59);
						endD.setSeconds(59);
						result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 0, context);
						ContentValues cVals = new ContentValues();
						cVals.put("UserID", userId);
						cVals.put("Syear", dateE);
						String tName = "yearTable";
						long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
					}
				}
			}
			else
			{
				String tempsql = "select count(Syear) as Num from yearTable where Syear='" + date + "' and UserID=" + userId;
				ArrayList<Dictionary> RunningDay = new ArrayList<Dictionary>();
				RunningDay = ds.ExecuteReader1(tempsql,context);
				String count = RunningDay.get(0).get("Num").toString();
				if (count.equals("0"))
				{
					Date startD = new Date(startDate.getYear(), 0, 1);
					startD.setHours(0);
					startD.setMinutes(0);
					startD.setSeconds(0);
					Date endD = new Date(startDate.getYear(), 11, 31);
					endD.setHours(23);
					endD.setMinutes(59);
					endD.setSeconds(59);
					result = downloadDataToDB(sessionId, startD, endD, client_vernumber, 0, context);
					ContentValues cVals = new ContentValues();
					cVals.put("UserID", userId);
					cVals.put("Syear", date);
					String tName = "yearTable";
					long rowNum = ds.ExecuteInsertSingle(cVals, context, tName);
				}
				
			}
		}
		
		return result;
	}
	
	
	/**
	 * @param sessionId
	 * @param startDate
	 * @param endDate
	 * @param client_vernumber
	 * @param datatype 0为XFIT_Day_Summary数据；1为XFIT_Per_Running数据；2为XFIT_Speed_Detail数据；3为XFIT_Tracking_Detail数据
	 * @param context
	 * @return 下载的行数(long)
	 * @throws ParseException 
	 */
	public long downloadDataToDB(String sessionId, Date startDate, Date endDate, String client_vernumber, int datatype, Context context) throws ParseException
	{
		long result = 0;
		String tName = "";
		
		if (datatype == 0)
		{
			tName = "XFIT_Day_Summary";
		}
		else if (datatype == 1 || datatype == 4)
		{
			tName = "XFIT_Per_Running";
		}
		else if (datatype == 2)
		{
			tName = "XFIT_Speed_Detail";
		}
		else if (datatype == 3)
		{
			tName = "XFIT_Tracking_Detail";
		}
		ArrayList<ContentValues> serverData = downloadData(sessionId, startDate, endDate, client_vernumber, datatype);
		if (serverData.size() == 0)
		{
			return result;
		}
		DBServices dbs = new DBServices();
		result = dbs.ExecuteInsertMultiple(serverData, context, tName);
		return result;
	}
	
	
	public int[] returnAllIDs(int userID, Context context)
	{
		
		String sql = "select ID from MonthWeekYearReport where UserId="+userID+" order by ID";
		DBServices ds = new DBServices();
		ArrayList<Dictionary> temppp = ds.ExecuteReader1(sql, context);
		int[] result = null;
		if (temppp.size() >= 1)
		{
			result = new int[temppp.size()];
			for (int i = 0; i < temppp.size(); i++)
			{
				result[i] = Integer.parseInt(temppp.get(i).get("ID").toString());
			}
		}
		return result;
	}
	public boolean whetherDownload(Context context, int tabletype, int userid)
	{
		boolean result = false;
		String sql = "";
		String sql1 = "select count(*) as Num from XFIT_Day_Summary where userid=" + userid;
		String sql2 = "select count(*) as Num from XFIT_Per_Running where userid=" + userid;
		String sql3 = "select count(*) as Num from XFIT_Speed_Detail where userid=" + userid;
		String sql4 = "select count(*) as Num from XFIT_Tracking_Detail where userid=" + userid;
		
		if (tabletype == 0)
		{
			sql = sql1;
		}
		else if (tabletype == 1)
		{
			sql = sql2;
		}
		else if (tabletype == 2)
		{
			sql = sql3;
		}
		else if (tabletype == 3)
		{
			sql = sql4;
		}
		DBServices ds = new DBServices();
		ArrayList<Dictionary> tempReeee = ds.ExecuteReader1(sql,context);
		
		if (tempReeee.size() >= 1)
		{
			int tre = Integer.parseInt(tempReeee.get(0).get("Num").toString());
			if (tre <= 0)
			{
				result = true;
			}
		}
		return result;
	}

}
